﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ColorApplication.Helper;
using System.Net;


namespace ColorApplication
{
    public partial class FileUpload11 : mht
    {
        Random rndQuery = new Random();
        Datas data = new Datas();


        #region Class
        [Serializable()]
        private class Datas
        {
            public string imagePath;
            public string csvFileName;
            public string fileName;
            public string imgFileName;
            public string pieFileName;
            public decimal wantedFamilyMark;
            public int fileDbId;

            public string imagePath2;
            public string csvFileName2;
            public string fileName2;
            public string imgFileName2;
            public string pieFileName2;
            public decimal wantedFamilyMark2;
            public int fileDbId2;

            public DataTable csvdatatable;
            public DataTable colordatatable;
            public DataTable subColorDetailsdatatable;
            public DataTable colorBrightNessdatatable;
            public DataTable colorAttributedatatable;
            public DataTable attributeFamiliesdatatable;
            public DataTable whiteColorNeutralization;
            public DataTable colorAreaPercentagedatatable;

            public DataTable csvdatatable2;
            public DataTable colordatatable2;
            public DataTable subColorDetailsdatatable2;
            public DataTable colorBrightNessdatatable2;
            public DataTable colorAttributedatatable2;
            public DataTable attributeFamiliesdatatable2;
            public DataTable whiteColorNeutralization2;
            public DataTable colorAreaPercentagedatatable2;


            public bool first { get; set; }

            public bool second { get; set; }
        }
        #endregion

        #region Properties

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public bool first
        {
            get
            {
                return data.first;
            }
            set
            {
                data.first = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public int FileDbId
        {
            get
            {
                data.fileDbId = (int)Session["FileDbId" + "1"];
                return data.fileDbId;
            }
            set
            {
                Session["FileDbId" + "1"] = value;
                data.fileDbId = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public int FileDbId2
        {
            get
            {
                data.fileDbId2 = (int)Session["FileDbId" + "2"];
                return data.fileDbId2;
            }
            set
            {
                Session["FileDbId" + "2"] = value;
                data.fileDbId2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public bool second
        {
            get
            {
                return data.second;
            }
            set
            {
                data.second = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string ImagePath
        {
            get
            {
                data.imagePath = Session["imagePath" + "1"] as string;
                return data.imagePath;
            }
            set
            {
                Session["imagePath" + "1"] = value;
                data.imagePath = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string CsvFileName
        {
            get
            {
                return data.csvFileName;
            }
            set
            {
                data.csvFileName = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string FileName
        {
            get
            {
                return data.fileName;
            }
            set
            {
                data.fileName = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string ImgFileName
        {
            get
            {
                data.imgFileName = Session["imgFilename" + "1"] as string;
                return data.imgFileName;
            }
            set
            {
                Session["imgFilename" + "1"] = value;
                data.imgFileName = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string PieFileName
        {
            get
            {
                data.pieFileName = Session["pieFileName1"] as string;
                return data.pieFileName;
            }
            set
            {
                Session["pieFileName1"] = value;
                data.pieFileName = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(0)]
        [NotifyParentProperty(true)]
        public decimal WantedFamilyMark
        {
            get
            {
                if (Session["WantedFamilyMark"] != null)
                    data.wantedFamilyMark = Convert.ToDecimal(Session["WantedFamilyMark"]);
                return data.wantedFamilyMark;
            }
            set
            {
                Session["WantedFamilyMark"] = value;
                data.wantedFamilyMark = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable CsvDT
        {
            get
            {
                data.csvdatatable = Session["csvdatatable" + "1"] as DataTable;
                return data.csvdatatable;
            }
            set
            {
                data.csvdatatable = value;
                Session["csvdatatable" + "1"] = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorDT
        {
            get
            {
                data.colordatatable = Session["Colordatatable" + "1"] as DataTable;
                return data.colordatatable;
            }
            set
            {
                data.colordatatable = value;
                Session["Colordatatable" + "1"] = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable SubColorDetailsDT
        {
            get
            {
                return data.subColorDetailsdatatable;
            }
            set
            {
                data.subColorDetailsdatatable = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorBrightNessDT
        {
            get
            {
                return data.colorBrightNessdatatable;
            }
            set
            {
                data.colorBrightNessdatatable = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorAttributeDT
        {
            get
            {
                data.colorAttributedatatable = Session["ColorAttributedatatable" + "1"] as DataTable;
                return data.colorAttributedatatable;
            }
            set
            {
                Session["ColorAttributedatatable" + "1"] = value;
                data.colorAttributedatatable = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable AttributeFamiliesDT
        {
            get
            {
                data.attributeFamiliesdatatable = Session["AttributeFamiliesdatatable" + "1"] as DataTable;
                return data.attributeFamiliesdatatable;
            }
            set
            {
                Session["AttributeFamiliesdatatable" + "1"] = value;
                data.attributeFamiliesdatatable = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable WhiteColorNeutralization
        {
            get
            {
                return data.whiteColorNeutralization;
            }
            set
            {
                data.whiteColorNeutralization = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorAreaPercentageDT
        {
            get
            {
                return data.colorAreaPercentagedatatable;
            }
            set
            {
                data.colorAreaPercentagedatatable = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string ImagePath2
        {
            get
            {
                data.imagePath2 = Session["imagePath" + "2"] as string;
                return data.imagePath2;
            }
            set
            {
                Session["imagePath" + "2"] = value;
                data.imagePath2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string CsvFileName2
        {
            get
            {
                return data.csvFileName2;
            }
            set
            {
                data.csvFileName2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string FileName2
        {
            get
            {
                return data.fileName2;
            }
            set
            {
                data.fileName2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string ImgFileName2
        {
            get
            {
                data.imgFileName2 = Session["imgFilename" + "2"] as string;
                return data.imgFileName2;
            }
            set
            {
                Session["imgFilename" + "2"] = value;
                data.imgFileName2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public string PieFileName2
        {
            get
            {
                data.pieFileName2 = Session["pieFileName2"] as string;
                return data.pieFileName2;
            }
            set
            {
                Session["pieFileName2"] = value;
                data.pieFileName2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("Misc")]
        [DefaultValue(0)]
        [NotifyParentProperty(true)]
        public decimal WantedFamilyMark2
        {
            get
            {
                if (Session["WantedFamilyMark2"] != null)
                    data.wantedFamilyMark2 = Convert.ToDecimal(Session["WantedFamilyMark2"]);
                return data.wantedFamilyMark2;
            }
            set
            {
                Session["WantedFamilyMark2"] = value;
                data.wantedFamilyMark2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable CsvDT2
        {
            get
            {
                data.csvdatatable2 = Session["csvdatatable" + "2"] as DataTable;
                return data.csvdatatable2;
            }
            set
            {
                data.csvdatatable2 = value;
                Session["csvdatatable" + "2"] = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorDT2
        {
            get
            {
                data.colordatatable2 = Session["Colordatatable" + "2"] as DataTable;
                return data.colordatatable2;
            }
            set
            {
                data.colordatatable2 = value;
                Session["Colordatatable" + "2"] = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable SubColorDetailsDT2
        {
            get
            {
                return data.subColorDetailsdatatable2;
            }
            set
            {
                data.subColorDetailsdatatable2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorBrightNessDT2
        {
            get
            {
                return data.colorBrightNessdatatable2;
            }
            set
            {
                data.colorBrightNessdatatable2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorAttributeDT2
        {
            get
            {
                data.colorAttributedatatable2 = Session["ColorAttributedatatable" + "2"] as DataTable;
                return data.colorAttributedatatable2;
            }
            set
            {
                Session["ColorAttributedatatable" + "2"] = value;
                data.colorAttributedatatable2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable AttributeFamiliesDT2
        {
            get
            {
                data.attributeFamiliesdatatable2 = Session["AttributeFamiliesdatatable" + "2"] as DataTable;
                return data.attributeFamiliesdatatable2;
            }
            set
            {
                Session["AttributeFamiliesdatatable" + "2"] = value;
                data.attributeFamiliesdatatable2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable WhiteColorNeutralization2
        {
            get
            {
                return data.whiteColorNeutralization2;
            }
            set
            {
                data.whiteColorNeutralization2 = value;
                SaveControlState();
            }
        }

        [Browsable(true)]
        [Category("DataTables")]
        [DefaultValue(null)]
        [NotifyParentProperty(true)]
        public DataTable ColorAreaPercentageDT2
        {
            get
            {
                return data.colorAreaPercentagedatatable2;
            }
            set
            {
                data.colorAreaPercentagedatatable2 = value;
                SaveControlState();
            }
        }
        #endregion

        #region Methods

        protected override void OnInit(System.EventArgs e)
        {
            Page.RegisterRequiresControlState(this);
            base.OnInit(e);
        }

        protected override object SaveControlState()
        {
            return this.data;
        }

        protected override void LoadControlState(object savedState)
        {
            data = new Datas();
            data = (Datas)savedState;
        }

        #endregion

        protected void Page_PreRender(object sender, EventArgs e)
        {


            /************************Start Fill Wanted Family List  changed by hanumant ************/
            FillWantedFamilyList();
            /******************************* End Fill Wanted Family List changed by hanumant  **********************************/



            /**************Changed by hanumant remove ispostback Propeties**************************/
            //Wanted family list selected by user while uploading images in (compare Two Pictures)
            List<WantedAttributeFamily> wantedFamilyList = Session["wantedFamilyList"] as List<WantedAttributeFamily>;
            if (wantedFamilyList != null && wantedFamilyList.Count > 0)
            {
                //whether any of marks of wanted family greater than 0 for the image
                if (WantedFamilyMark > 0 || WantedFamilyMark2 > 0)
                {
                    //display Better picture message label 
                    BestPicture.Visible = true;
                    BestPicture0.Visible = true;

                    //specify which of the picture is better
                    if (WantedFamilyMark > WantedFamilyMark2)
                    {
                        BestPicture.Text = string.Format(BestPicture.Text, LabelImageName.Text);
                        BestPicture0.Text = string.Format(BestPicture0.Text, LabelImageName.Text);
                    }
                    else if (WantedFamilyMark < WantedFamilyMark2)
                    {
                        BestPicture.Text = string.Format(BestPicture.Text, LabelImageName2.Text);
                        BestPicture0.Text = string.Format(BestPicture0.Text, LabelImageName2.Text);
                    }
                    else if (WantedFamilyMark == WantedFamilyMark2)
                    {
                        BestPicture.Text = "Both picture are equal.";
                        BestPicture0.Text = "Both picture are equal.";
                    }

                }
                else //none of the picture fits in wanted family attributes
                {
                    BestPicture.Visible = true;
                    BestPicture0.Visible = true;

                    BestPicture.Text = "The pictures do not fit to the selected attributes.";
                    BestPicture0.Text = "The pictures do not fit to the selected attributes.";
                }
            }

            if (IsPostBack)
            { }

            //Script to validate selection count of attributes
            string script = @"function validateSelect(sender, args) {
                                var attributeTb = document.getElementById('" + grdVwAttribute.ClientID + @"');
                                if(attributeTb)
                                {               
                                    var chkArray = attributeTb.getElementsByTagName('input');
                                    var count = 0;
                                    for (var i = 0; i < chkArray.length; i++) {
                                        if (chkArray[i].checked)
                                            count++;
                                    }
                                    if (count > " + ConfigurationManager.AppSettings["WantedFamilyCount"].ToString() + @") {
                                        args.IsValid = false;
                                    }
                                    else
                                        args.IsValid = true;
                                }
                            }
                            function validateRequired(source, argument) {
                                var FileUpload1 = document.getElementById('" + FileUpload1.ClientID + @"');
                                var FileUpload2 = document.getElementById('" + FileUpload2.ClientID + @"');

                                argument.IsValid = (FileUpload1.value != '' || FileUpload2.value != '');

        }";


            ScriptManager.RegisterClientScriptBlock(
                this,
                typeof(Page),
                "ToggleScript" + this.ClientID,
                script,
                true);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Clear Error And Success Label
            ClearAll();

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ref"]) && Request.QueryString["ref"] == "new")
                {
                    //to upload new file
                    ImagePath = null;
                    ImagePath2 = null;
                    CsvDT = null;
                    CsvDT2 = null;
                    ImgFileName = null;
                    ImgFileName2 = null;
                    Session["wantedFamilyList"] = null;
                    Session.Abandon();
                }

                //Find better picture in two
                if (!string.IsNullOrEmpty(Request.QueryString["opt"]) && Request.QueryString["opt"] == "two")
                {
                    //changing display style required to upload two pictures
                    tbFileupload1.Style[HtmlTextWriterStyle.Display] = "";
                    tbFileupload2.Style[HtmlTextWriterStyle.Display] = "";
                    tbUploads.Style[HtmlTextWriterStyle.Display] = "";
                    tbUrl.Style[HtmlTextWriterStyle.Display] = "none";
                    lblHeading.Text = "Please choose two pictures to analyze";
                    //    align="center"
                    TDForResultSaveButton.Align = "right";

                    List<WantedAttributeFamily> wantedFamilyList;
                    string selectedAttributes = string.Empty;
                    wantedFamilyList = Session["wantedFamilyList"] as List<WantedAttributeFamily>;
                    if (wantedFamilyList != null)
                    {
                        if (wantedFamilyList.Count > 0)
                        {
                            foreach (WantedAttributeFamily item in wantedFamilyList)
                            {
                                selectedAttributes += item.AttributeFamily + ", ";
                            }
                            lblSelected.Visible = true;
                            lblSelected.Text = string.Format(lblSelected.Text, selectedAttributes);
                        }
                    }

                }
                else if (!string.IsNullOrEmpty(Request.QueryString["opt"]) && Request.QueryString["opt"] == "url")
                {
                    //Changing display style required to analysis website
                    tbUploads.Style[HtmlTextWriterStyle.Display] = "none";
                    tbUrl.Style[HtmlTextWriterStyle.Display] = "";
                    lblHeading.Text = "Please enter any URL to analyze";
                }
                else
                {
                    //changing display style required to upload single picture
                    tbFileupload1.Style[HtmlTextWriterStyle.Display] = "";
                    tbFileupload2.Style[HtmlTextWriterStyle.Display] = "none";
                    tbUploads.Style[HtmlTextWriterStyle.Display] = "";
                    tbUrl.Style[HtmlTextWriterStyle.Display] = "none";
                    lblHeading.Text = "Please choose a picture to analyze";
                    litFirstImg.Text = "Image:";
                }


                //Session.Remove("wantedFamilyList");

                /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                try
                {
                    //Getting Common message added by admin to display
                    lblCommonMessage.Text = GetCommonMessage();
                }
                catch { }
                /*********************end Change made by hanumant Apply try cacth for handling error *************/

                //adding clientclick to savebutton to display preloader
                SaveButton.OnClientClick += "PreloadPage();";

                /**************************Start Change Made by Hanumant For Register onchange for File Upload When two File Selected************/
                if (Request.QueryString["opt"] == "two")
                {
                    //adding clientclick to fileuploader to display family attributes to select (wanted families)
                    FileUpload1.Attributes.Add("onchange", "javascript:toggleSelect1();");
                    FileUpload2.Attributes.Add("onchange", "javascript:toggleSelect2();");

                    SaveButton.Text = "Find the best from two pictures";
                }
                /**************************End Change Made by Hanumant For Register onchange for File Upload When two File Selected************/
                //adding client validtion function to custom validators
                CustomValidator1.ClientValidationFunction = "validateSelect";
                CustomValidator2.ClientValidationFunction = "validateRequired";

                //for first time page load changing display properties
                Panel1.Style.Add("display", "none");
                Panel2.Style.Add("display", "none");
                lblCommonMessage.Style.Add("display", "none");
                CustomValidator1.ErrorMessage = "You can select maximum " + ConfigurationManager.AppSettings["WantedFamilyCount"].ToString() + " attribute families";

                //Show user the analysis results from session (session gets filled when file is uploaded first time) (file uploader 1 and URL)
                if (CsvDT != null && ImagePath != null)
                {
                    lblHeading.Text = "Analysis results";
                    DataTable csvdatatable = (DataTable)CsvDT;


                    /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                    try
                    {
                        //Get CSV Tab
                        SetCSV(csvdatatable);
                        // Get Color Tab 
                        SetColorTab(csvdatatable);
                        // Get SubColor Tab 
                        SetSubColorTab(csvdatatable);
                        // Get Color Brightness
                        SetColorBrightNess(csvdatatable);
                        // Get Brightness Level
                        SetColorAreaPercentagetab(csvdatatable);
                        // Get Color Attribute
                        SetColorAttributeTab(csvdatatable);
                        // Get Attribute Families 
                        SetAttributeFamiliesTab(csvdatatable);
                        // Get White Color Neutralization
                        SetWhiteColorNeutralisetab(csvdatatable);
                        // Get Contributed Color
                        SetContributedColorTab(csvdatatable);
                    }
                    catch (Exception ex)
                    {
                        Session.Abandon();
                        lblPageError.Text = ex.Message + " " + ex.StackTrace + "" + ex.ToString() + ". Please upload file again.";
                    }
                    /*********************End Change made by hanumant Apply try cacth for handling error *************/



                    //set image path of Image1 the query string is to preventing caching of image
                    Image1.ImageUrl = ImagePath.ToString() + "?uid=" + rndQuery.Next(0, 9999).ToString();
                    Image1.Style.Add(HtmlTextWriterStyle.Display, "");
                    trBtn.Style.Add(HtmlTextWriterStyle.Display, "");
                    TabContainer1.Style.Add(HtmlTextWriterStyle.Display, "");
                    LabelImageName.Style.Add(HtmlTextWriterStyle.Display, "block");
                    LabelImageName.Text = ImgFileName;
                    lblImgSize1.InnerText = getImageSize(Server.MapPath(ImagePath));

                    btnViewDetail.Visible = true;
                    //Panel1.Style.Add("display", "block");
                    lblCommonMessage.Style.Add("display", "block");
                    trUpload.Style[HtmlTextWriterStyle.Display] = "none";
                    trAfterUpload.Style[HtmlTextWriterStyle.Display] = "";
                    first = true;

                    if (Request.QueryString["opt"] == "url")
                    {
                        lblHeading.Text = "Result Of URL analysis.";
                        LabelImageName.Text = Session["Site_Url"].ToString();
                    }
                }
                //if the sessions are null and the page is loading first time after uploading the file. (file uploader 1 and URL)
                else if (ImgFileName != null)
                {
                    //Check whether go via payment is enabled
                    if (GetGoViaPayment())
                    {
                        if (!string.IsNullOrEmpty(Request.QueryString["txId"]))
                        {
                            //If payment is not successful it return url will contain Errorcode querystring
                            if (string.IsNullOrEmpty(Request.QueryString["ErrorCode"]))
                            {
                                /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                                try
                                {
                                    //Do the first file analysis step 2
                                    FirstFileStep2();
                                }
                                catch (Exception ex)
                                {
                                    Session.Abandon();
                                    lblPageError.Text = ex.Message + " " + ex.StackTrace + "" + ex.ToString() + ". Please upload file again."; ;
                                }
                                /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                            }
                            else
                            {
                                lblPageError.Text = Request.QueryString["ErrorText"];
                            }
                        }
                    }
                    else
                    {
                        /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                        try
                        {

                            //Do the first file analysis step 2
                            FirstFileStep2();
                            //check whether url or not
                            if (Request.QueryString["opt"] == "url")
                            {
                                lblHeading.Text = "Result Of URL analysis.";
                                LabelImageName.Text = Session["Site_Url"].ToString();
                                lblImgSize1.Visible = false;
                                divImgSize1.Visible = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            Session.Abandon();
                            lblPageError.Text = ex.Message + " " + ex.StackTrace + "" + ex.ToString() + ". Please upload file again."; ;
                        }
                        /*********************End Change made by hanumant Apply try cacth for handling error *************/
                    }
                }

                //Show user the analysis results from session (session gets filled when file is uploaded first time) (file uploader 2)
                if (CsvDT2 != null && ImagePath2 != null)
                {
                    lblHeading.Text = "Analysis results";
                    DataTable csvdatatable = (DataTable)CsvDT2;
                    /********************* Start Change made by hanumant Apply try cacth for handling error *************/
                    try
                    {

                        // Get Color Tab 
                        SetColorTab2(csvdatatable);
                        // Get SubColor Tab 
                        SetSubColorTab2(csvdatatable);
                        // Get Color Brightness
                        SetColorBrightNess2(csvdatatable);
                        // Get Brightness Level
                        SetColorAreaPercentagetab2(csvdatatable);
                        // Get Color Attribute
                        SetColorAttributeTab2(csvdatatable);
                        // Get Attribute Families 
                        SetAttributeFamiliesTab2(csvdatatable);
                        // Get White Color Neutralization
                        SetWhiteColorNeutralisetab2(csvdatatable);
                        // Get Contributed Color
                        SetContributedColorTab2(csvdatatable);
                    }
                    catch (Exception ex)
                    {
                        Session.Abandon();
                        lblPageError.Text = ex.Message + " " + ex.StackTrace + "" + ex.ToString() + ". Please upload file again."; ;
                    }
                    /*********************End Change made by hanumant Apply try cacth for handling error *************/

                    trBtn2.Style.Add(HtmlTextWriterStyle.Display, "");
                    TabContainer2.Style.Add(HtmlTextWriterStyle.Display, "");

                    Image2.ImageUrl = ImagePath2.ToString() + "?uid=" + rndQuery.Next(0, 9999).ToString();
                    Image2.Style.Add(HtmlTextWriterStyle.Display, "");
                    LabelImageName2.Style.Add(HtmlTextWriterStyle.Display, "block");
                    LabelImageName2.Text = ImgFileName2;
                    lblImgSize2.InnerText = getImageSize(Server.MapPath(ImagePath2));

                    btnViewDetail.Visible = true;
                    //Panel2.Style.Add("display", "block");
                    trUpload.Style[HtmlTextWriterStyle.Display] = "none";
                    trAfterUpload.Style[HtmlTextWriterStyle.Display] = "";
                    second = true;
                }
                else if (ImgFileName2 != null)
                {

                    if (GetGoViaPayment())
                    {
                        if (!string.IsNullOrEmpty(Request.QueryString["txId"]))
                        {
                            //If payment is not successful it return url will contain Errorcode querystring
                            if (string.IsNullOrEmpty(Request.QueryString["ErrorCode"]))
                            {
                                /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                                try
                                {
                                    SecondFileStep2();
                                }
                                catch (Exception ex)
                                {
                                    Session.Abandon();
                                    lblPageError.Text = ex.ToString() + ". Please upload file again."; ;
                                }
                            }
                            else
                            {
                                lblPageError.Text = Request.QueryString["ErrorText"];
                            }
                        }
                    }
                    else
                    {
                        /*********************Start Change made by hanumant Apply try cacth for handling error *************/
                        try
                        {
                            SecondFileStep2();
                            /*********************End Change made by hanumant Apply try cacth for handling error *************/
                        }
                        catch (Exception ex)
                        {
                            Session.Abandon();
                            lblPageError.Text = ex.ToString() + " " + ex.StackTrace + ". Please upload file again."; ;
                        }
                        /*********************End Change made by hanumant Apply try cacth for handling error *************/
                    }
                }

                //Display first image or not
                if (first)
                    pnlImg1.Style[HtmlTextWriterStyle.Display] = "";
                else
                    pnlImg1.Style[HtmlTextWriterStyle.Display] = "none";

                //Display second Image or not
                if (second)
                    pnlImg2.Style[HtmlTextWriterStyle.Display] = "";
                else
                    pnlImg2.Style[HtmlTextWriterStyle.Display] = "none";

                //Check whether two files were uploaded
                if (first && second)
                {
                    pnlImg1.Style[HtmlTextWriterStyle.Display] = "";
                    pnlImg2.Style[HtmlTextWriterStyle.Display] = "";
                    pnlImg1.CssClass = "divImg1MainDouble bigFont";
                    pnlImg2.CssClass = "divImg1MainDouble2 bigFont";

                    divImgMain1.Attributes["class"] = "imgMainDivDouble";
                    divImgMain2.Attributes["class"] = "imgMainDivDouble";

                    divImg1.Attributes["class"] = "imgImgDivDouble";
                    divImg2.Attributes["class"] = "imgImgDivDouble";

                    divImgSize1.Attributes["class"] = "imgImgSizeDouble";
                    divImgSize2.Attributes["class"] = "imgImgSizeDouble";

                    trBtn.Attributes["class"] = "imgBtnDivDouble";
                    trBtn2.Attributes["class"] = "imgBtnDivDouble";
                    Panel1.Style.Add("width", "48.4%");
                    Panel2.Style.Add("width", " 48.5%");
                    Panel2.Style.Add("margin-left", "3%");

                    DownloadButton.Width = new Unit(150, UnitType.Pixel);
                    DownloadButton2.Width = new Unit(150, UnitType.Pixel);
                    WebFileButton.Width = new Unit(150, UnitType.Pixel);
                    WebFileButton2.Width = new Unit(150, UnitType.Pixel);
                    ViewHtmlButton.Width = new Unit(150, UnitType.Pixel);
                    ViewHtmlButton2.Width = new Unit(150, UnitType.Pixel);

                    DownloadButton.Style[HtmlTextWriterStyle.MarginBottom] = "11px";
                    DownloadButton2.Style[HtmlTextWriterStyle.MarginBottom] = "11px";
                    WebFileButton.Style[HtmlTextWriterStyle.MarginBottom] = "11px";
                    WebFileButton2.Style[HtmlTextWriterStyle.MarginBottom] = "11px";
                    ViewHtmlButton.Style[HtmlTextWriterStyle.MarginBottom] = "11px";
                    ViewHtmlButton2.Style[HtmlTextWriterStyle.MarginBottom] = "11px";

                    Session["WantedFamilyMark"] = WantedFamilyMark;
                    Session["WantedFamilyMark2"] = WantedFamilyMark2;

                }


                if (CsvFileName != null)
                {
                    string filename = CsvFileName.ToString();
                    FileName = filename;
                }
                //check whether admin is using site
                if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["id"] == ConfigurationManager.AppSettings["AdminID"].ToString())
                {
                    ColorAttributeTabPanel.Visible = true;
                    ColorBrightnessTabPanel.Visible = true;
                    SubColorTabPanel.Visible = true;
                    ColorTabPanel.Visible = true;
                    WhiteColorNeutralizationPanel.Visible = true;
                    BrightnessLevelPanel.Visible = true;

                    ColorAttributeTabPanel2.Visible = true;
                    ColorBrightnessTabPanel2.Visible = true;
                    SubColorTabPanel2.Visible = true;
                    ColorTabPanel2.Visible = true;
                    WhiteColorNeutralizationPanel2.Visible = true;
                    BrightnessLevelPanel2.Visible = true;

                    CSVTabPanel.Visible = true;
                    CSVTabPanel2.Visible = true;

                    DownloadButton.Visible = true;
                    DownloadButton2.Visible = true;
                }
                else
                {
                    CSVTabPanel.Visible = false;
                    CSVTabPanel2.Visible = false;
                    AttributeFamiliesPanel.Visible = true;
                    AttributeFamiliesPanel2.Visible = true;
                    TabContainer1.ActiveTabIndex = 5;
                    TabContainer2.ActiveTabIndex = 5;

                    DownloadButton.Visible = false;
                    DownloadButton2.Visible = false;
                }
            }

        }

        //private String queryMPITransaction(string transaction_id)
        //{
        //    if ((transaction_id == "") || (transaction_id == null))
        //        return "transaction ID is missing";

        //    string terminal_id = ConfigurationManager.AppSettings["TerminalId"];
        //    string merchant_id = ConfigurationManager.AppSettings["MerchantId"];
        //    string user = ConfigurationManager.AppSettings["User"];
        //    string password = ConfigurationManager.AppSettings["Password"];
        //    string cg_gateway_url = ConfigurationManager.AppSettings["CG_Gateway_Url"];

        //    //string terminal_id = "0962922";
        //    //string merchant_id = "1";
        //    //string user = "israel";
        //    //string password = "Israeli1.";
        //    //string cg_gateway_url = "https://cguat2.creditguard.co.il/xpo/Relay";

        //    Random rand = new Random();
        //    string uniqueID = DateTime.Now.ToString("yyyyddMM") + rand.Next(0, 1000);
        //    String result = "";
        //    String poststring = "user=" + user +
        //                          "&password=" + password +
        //                          "&int_in=<ashrait>" +
        //                          "<request>" +
        //                           "<language>ENG</language>" +
        //                           "<command>inquireTransactions</command>" +
        //                           "<inquireTransactions>" +
        //                            "<terminalNumber>" + terminal_id + "</terminalNumber>" +
        //                            "<mainTerminalNumber/>" +
        //                            "<queryName>mpiTransaction</queryName>" +
        //                            "<mid>" + merchant_id + "</mid>" +
        //                            "<mpiTransactionId>" + transaction_id + "</mpiTransactionId>" +
        //                            "<userData1/>" +
        //                            "<userData2/>" +
        //                            "<userData3/>" +
        //                            "<userData4/>" +
        //                            "<userData5/>" +
        //                           "</inquireTransactions>" +
        //                          "</request>" +
        //                         "</ashrait>";


        //    StreamWriter myWriter = null;

        //    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(cg_gateway_url);
        //    objRequest.Method = "POST";
        //    objRequest.ContentLength = poststring.Length;
        //    objRequest.ContentType = "application/x-www-form-urlencoded";

        //    try
        //    {
        //        myWriter = new StreamWriter(objRequest.GetRequestStream());
        //        myWriter.Write(poststring);
        //    }
        //    catch (Exception e)
        //    {
        //        return e.Message;
        //    }
        //    finally
        //    {
        //        myWriter.Close();
        //    }

        //    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        //    using (StreamReader sr =
        //       new StreamReader(objResponse.GetResponseStream()))
        //    {
        //        result = sr.ReadToEnd();

        //        // Close and clean up the StreamReader
        //        sr.Close();
        //    }


        //    XmlDocument doc = new XmlDocument();
        //    try
        //    {
        //        doc.LoadXml(result);
        //    }
        //    catch
        //    {
        //        return result;
        //    }

        //    string response = "";
        //    try
        //    {

        //        response += "Result Code: " + doc.GetElementsByTagName("result")[1].InnerText;
        //        //response += "<br />Unique ID: " + doc.GetElementsByTagName("uniqueid")[0].InnerText;
        //        //response += "<br />Language Code: " + doc.GetElementsByTagName("languageCode")[0].InnerText;
        //        //response += "<br />Auth Number: " + doc.GetElementsByTagName("authNumber")[0].InnerText;
        //        //response += "<br />Card Token: " + doc.GetElementsByTagName("cardId")[0].InnerText;
        //        //response += "<br />Card Expiration: " + doc.GetElementsByTagName("cardExpiration")[0].InnerText;
        //        //response += "<br />Card Mask: " + doc.GetElementsByTagName("cardMask")[0].InnerText;
        //        //response += "<br />Personal ID: " + doc.GetElementsByTagName("personalId")[0].InnerText;
        //        //response += "<br />Transaction ID: " + doc.GetElementsByTagName("mpiTransactionId")[0].InnerText;
        //    }
        //    catch (Exception)
        //    {
        //    }


        //    return response;

        //    //Random rand = new Random();
        //    //string uniqueID = DateTime.Now.ToString("yyyyddMM") + rand.Next(0, 1000);
        //    //String result = "";
        //    //String poststring = "user=" + user +
        //    //                      "&password=" + password +
        //    //                      "&int_in=<ashrait>" +
        //    //                      "<request>" +
        //    //                       "<language>ENG</language>" +
        //    //                       "<command>inquireTransactions</command>" +
        //    //                       "<inquireTransactions>" +
        //    //                        "<terminalNumber>" + terminal_id + "</terminalNumber>" +
        //    //                        "<mainTerminalNumber/>" +
        //    //                        "<queryName>mpiTransaction</queryName>" +
        //    //                        "<mid>" + merchant_id + "</mid>" +
        //    //                        "<mpiTransactionId>" + transaction_id + "</mpiTransactionId>" +
        //    //                        "<userData1/>" +
        //    //                        "<userData2/>" +
        //    //                        "<userData3/>" +
        //    //                        "<userData4/>" +
        //    //                        "<userData5/>" +
        //    //                       "</inquireTransactions>" +
        //    //                      "</request>" +
        //    //                     "</ashrait>";


        //    //StreamWriter myWriter = null;

        //    //HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(cg_gateway_url);
        //    //objRequest.Method = "POST";
        //    //objRequest.ContentLength = poststring.Length;
        //    //objRequest.ContentType = "application/x-www-form-urlencoded";

        //    //try
        //    //{
        //    //    myWriter = new StreamWriter(objRequest.GetRequestStream());
        //    //    myWriter.Write(poststring);
        //    //}
        //    //catch (Exception e)
        //    //{
        //    //    return e.Message;
        //    //}
        //    //finally
        //    //{
        //    //    myWriter.Close();
        //    //}

        //    //HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        //    //using (StreamReader sr =
        //    //   new StreamReader(objResponse.GetResponseStream()))
        //    //{
        //    //    result = sr.ReadToEnd();

        //    //    // Close and clean up the StreamReader
        //    //    sr.Close();
        //    //}


        //    //XmlDocument doc = new XmlDocument();
        //    //doc.LoadXml(result);
        //    //XmlNodeList Nodes = doc.GetElementsByTagName("statusText");
        //    //string response = Nodes[0].InnerText;
        //    //return response;
        //}

        public void ClearAll()
        {
            // Clear Error And Success Label
            ErrorLabel.Text = "";
            SuccesLabel.Text = "";

        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            //variable to check which image is uploaded
            //bool first = false;
            //bool second = false;
            try
            {
                //do file upload step 1 if file uploader 1 has file
                //if (FileUpload1.HasFile)
                //{
                    FirstFileStep1();
                    //// function to fill the wantedfamilylist session
                    //FillWantedFamilyList();
                    Session["IsDemo"] = true;
                //}
            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message + "<br/>" + err.StackTrace.ToString();
            }
            try
            {
                //do file upload step 1 if file uploader 2 has file
                if (FileUpload2.HasFile)
                {
                    SecondFileStep1();
                    //SecondFile();
                    FillWantedFamilyList();
                }
            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message + "<br/>" + err.StackTrace.ToString();
            }

            // check whether go via payment is enabled
            if (GetGoViaPayment())
                Response.Redirect("~/CreateTransaction.aspx");
            else
                Response.Redirect("~/" + Request.Url.PathAndQuery.Replace("&ref=new", "").Replace("ref=new&", "").Replace("?ref=new", "").Replace("ref=new", ""));

        }

        /// <summary>
        /// Function to get "go via payment" is enabled or not
        /// </summary>
        /// <returns></returns>
        private bool GetGoViaPayment()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            // Get Reduce White Color Percentage
            bool GoViaPayment = false;

            if (ds.Tables[0].Rows[0]["GoViaPayment"] != DBNull.Value)
                GoViaPayment = Convert.ToBoolean(ds.Tables[0].Rows[0]["GoViaPayment"]);

            return GoViaPayment;
        }

        /// <summary>
        /// function to fill selected wantedfamilyattributes
        /// </summary>
        private void FillWantedFamilyList()
        {

            List<WantedAttributeFamily> wantedFamilyList = new List<WantedAttributeFamily>();
            if (Session["wantedFamilyList"] == null)
            {
                string selectedAttributes = string.Empty;
                foreach (GridViewRow row in grdVwAttribute.Rows)
                {
                    CheckBox chk = row.FindControl("chk") as CheckBox;
                    if (chk.Checked)
                    {
                        DropDownList ddlAppearance = row.FindControl("ddlAppearance") as DropDownList;
                        Label lblAttributeFamily = row.FindControl("lblAttributeFamily") as Label;
                        WantedAttributeFamily wantedFamily = new WantedAttributeFamily();
                        wantedFamily.AttributeFamily = lblAttributeFamily.Text;
                        wantedFamily.AppearanceValue = Convert.ToInt32(ddlAppearance.SelectedValue);
                        selectedAttributes += lblAttributeFamily.Text + ", ";
                        wantedFamilyList.Add(wantedFamily);
                    }
                }
                if (selectedAttributes.Length > 0)
                    selectedAttributes = selectedAttributes.Substring(0, selectedAttributes.Length - 2);
                Session["wantedFamilyList"] = wantedFamilyList;

                if (wantedFamilyList.Count > 0)
                {
                    lblSelected.Visible = true;
                    lblSelected.Text = string.Format(lblSelected.Text, selectedAttributes);
                }
            }
            else
            {

                string selectedAttributes = string.Empty;
                wantedFamilyList = Session["wantedFamilyList"] as List<WantedAttributeFamily>;
                if (wantedFamilyList.Count > 0)
                {
                    foreach (WantedAttributeFamily item in wantedFamilyList)
                    {
                        selectedAttributes += item.AttributeFamily + ", ";
                    }
                    lblSelected.Visible = true;
                    lblSelected.Text = string.Format(lblSelected.Text, selectedAttributes);
                }
            }
        }

        private void FirstFileStep1()
        {
            //string filename = Path.GetFileName(FileUpload1.FileName).Replace(" ", "");

            //if (File.Exists(Server.MapPath("~/CApplication/") + filename))
            //{
            //    File.Delete(Server.MapPath("~/CApplication/") + filename);
            //}

            ////Save file1 to server 
            //FileUpload1.SaveAs(Server.MapPath("~/CApplication/") + filename);

            ////saving file name to session ImgFileName
            //ImgFileName = filename;
            ImgFileName = "shlomo.jpg";
        }

        private void FirstFileStep2()
        {
            //removing image url from Image control
            Image1.ImageUrl = "";
            DeleteCsvFile();

            lblHeading.Text = "Analysis results";

            lblWhiteNeuMessage.Visible = true;
            //getting file name from session 
            string filename = ImgFileName;

            //creating imgFile info object for further purpose
            FileInfo imgFile = new FileInfo(Server.MapPath("~/CApplication/") + filename);
            //getting file name without extension
            string filenameWithOutEx = filename.Replace(imgFile.Extension, ""); //Path.GetFileNameWithoutExtension(Server.MapPath("~/CApplication/") + filename).Replace(" ", "");

            //Excel file name for this image generated automatically by EXE
            string excelfilename = filenameWithOutEx + ".csv";
            //Delete  excel file if exists
            if (File.Exists(Server.MapPath("~/CApplication/") + excelfilename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + excelfilename);
            }

            string userFileName = filename;
            //Creating Thumbnail and Saving image for download purpose
            if (File.Exists(Server.MapPath("~/UpldImage/") + userFileName))
            {
                try
                {
                    File.Delete(Server.MapPath("~/UpldImage/") + userFileName);
                }
                catch (Exception)
                {
                    Random rnd = new Random();
                    userFileName = rnd.Next(0, 9999).ToString() + userFileName;
                }
            }

            System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("~/CApplication/") + filename);
            int thumbWidth = 150;
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            decimal r = (Convert.ToDecimal(srcHeight) / Convert.ToDecimal(srcWidth));
            int thumbHeight = Convert.ToInt32(decimal.Parse(thumbWidth.ToString()) * r);
            Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
            gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
            bmp.Save(Server.MapPath("~/UpldImage/") + userFileName);
            bmp.Dispose();
            image.Dispose();

            //Inserting to table adminreport. Size is in Bytes.
            FileDbId = InsertAdminReport(userFileName, Convert.ToDecimal(imgFile.Length));

            //Running EXE to get analysis of the uploaded image file
            string execlsheetname = filenameWithOutEx;
            Process runMap = new Process();
            runMap.StartInfo.WorkingDirectory = Server.MapPath("~/");
            runMap.StartInfo.FileName = Server.MapPath("~/CApplication/c.exe");
            runMap.StartInfo.Arguments = Server.MapPath("~/CApplication/") + filename;
            runMap.Start();
            runMap.WaitForExit();
            runMap.Close();

            //Get output from CSV file and getting the data in datatable and saving it in csvdatatable session
            ExcelConnection(excelfilename, execlsheetname);

            //Set Filename in Session for Download Purpose
            FileName = excelfilename;
            ImgFileName = userFileName;

            ////Delete Image File 
            //if (File.Exists(Server.MapPath("~/CApplication/") + filename))
            //{
            //    File.Delete(Server.MapPath("~/CApplication/") + filename);

            //}

            string htmlfilename = filenameWithOutEx + ".html";
            // Delete html  File 
            if (File.Exists(Server.MapPath("~/CApplication/") + htmlfilename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + htmlfilename);

            }
            string csvfilename = filenameWithOutEx + ".csv";
            // Show data to Grid
            if (File.Exists(Server.MapPath("~/CApplication/") + csvfilename))
            {
                DataTable csvdatatable = new DataTable();
                using (CsvReader csvData = new CsvReader(Server.MapPath("~/CApplication/" + csvfilename)))
                {
                    // set GridView to use DataTable returned from parser as the source
                    // for it's data. True is passed in to signify that file contains a
                    // header row which will name returned DataColumn's based on values
                    // read in from header row.

                    CsvDT = csvData.ReadIntoDataTable();
                    csvdatatable = csvData.ReadIntoDataTable();

                    // Get Color Tab 
                    SetColorTab(csvdatatable);
                    // Get SubColor Tab 
                    SetSubColorTab(csvdatatable);
                    // Get Color Brightness
                    SetColorBrightNess(csvdatatable);
                    // Get Brightness Level
                    SetColorAreaPercentagetab(csvdatatable);
                    // Get Color Attribute
                    SetColorAttributeTab(csvdatatable);
                    // Get Attribute Families 
                    SetAttributeFamiliesTab(csvdatatable);
                    // Get White Color Neutralization
                    SetWhiteColorNeutralisetab(csvdatatable);
                    // Get Contributed Color
                    SetContributedColorTab(csvdatatable);
                    //to clear the selections of marked families.
                    grdVwAttribute.DataBind();

                    trBtn.Style.Add(HtmlTextWriterStyle.Display, "");
                    TabContainer1.Style.Add(HtmlTextWriterStyle.Display, "");
                } // dispose of parser

                // Write Csv File to Column
                using (CsvWriter csvwriter = new CsvWriter())
                {
                    csvwriter.WriteCsv(csvdatatable, Server.MapPath("~/CApplication/" + csvfilename));

                }
                CsvFileName = csvfilename;
                //byte[] filedate = File.ReadAllBytes(Server.MapPath("~/CApplication/" + csvfilename));
                //Session["Filedata"] = filedate;

                // Delete csv  File 
                if (File.Exists(Server.MapPath("~/CApplication/") + csvfilename))
                {
                    File.Delete(Server.MapPath("~/CApplication/") + csvfilename);

                }

                ImagePath = "~/UpldImage/" + userFileName;
                Image1.ImageUrl = "~/UpldImage/" + userFileName + "?uid=" + rndQuery.Next(0, 9999).ToString();
                Image1.Style.Add(HtmlTextWriterStyle.Display, "");
                LabelImageName.Style.Add(HtmlTextWriterStyle.Display, "block");
                LabelImageName.Text = userFileName;
                lblImgSize1.InnerText = getImageSize(Server.MapPath(ImagePath));

                SuccesLabel.Text = "Upload status: File uploaded!";

                btnViewDetail.Visible = true;
                //Panel1.Style.Add("display", "block");
                lblCommonMessage.Style.Add("display", "block");
                trUpload.Style[HtmlTextWriterStyle.Display] = "none";
                trAfterUpload.Style[HtmlTextWriterStyle.Display] = "";
                first = true;
            }
        }

        private void SecondFileStep1()
        {
            string filename = Path.GetFileName(FileUpload2.FileName).Replace(" ", "");

            if (File.Exists(Server.MapPath("~/CApplication/") + filename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + filename);
            }

            FileUpload2.SaveAs(Server.MapPath("~/CApplication/") + filename);

            ImgFileName2 = filename;
        }

        private void SecondFileStep2()
        {
            Image2.ImageUrl = "";

            DeleteCsvFile2();

            lblHeading.Text = "Analysis results";

            lblWhiteNeuMessage2.Visible = true;
            string filename = ImgFileName2;
            FileInfo imgFile2 = new FileInfo(Server.MapPath("~/CApplication/") + filename);
            string filenameWithOutEx = filename.Replace(imgFile2.Extension, ""); //Path.GetFileNameWithoutExtension(FileUpload2.FileName).Replace(" ", "");
            string excelfilename = filenameWithOutEx + ".csv";
            if (File.Exists(Server.MapPath("~/CApplication/") + excelfilename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + excelfilename);
            }

            string userFileName = filename;
            //Creating Thumbnail and Saving image for download purpose
            if (File.Exists(Server.MapPath("~/UpldImage/") + userFileName))
            {
                try
                {
                    File.Delete(Server.MapPath("~/UpldImage/") + userFileName);

                }
                catch (Exception)
                {
                    Random rnd = new Random();
                    userFileName = rnd.Next(0, 9999).ToString() + userFileName;
                }
            }

            System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("~/CApplication/") + filename);
            int thumbWidth = 150;
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            decimal r = (Convert.ToDecimal(srcHeight) / Convert.ToDecimal(srcWidth));
            int thumbHeight = Convert.ToInt32(decimal.Parse(thumbWidth.ToString()) * r);
            Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);

            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
            gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);

            bmp.Save(Server.MapPath("~/UpldImage/") + userFileName);

            bmp.Dispose();
            image.Dispose();


            //Inserting to table adminreport. Size is in MB.
            FileDbId2 = InsertAdminReport(userFileName, Convert.ToDecimal(imgFile2.Length));

            string execlsheetname = filenameWithOutEx;
            Process runMap = new Process();
            runMap.StartInfo.WorkingDirectory = Server.MapPath("~/");
            runMap.StartInfo.FileName = Server.MapPath("~/CApplication/c.exe");
            runMap.StartInfo.Arguments = Server.MapPath("~/CApplication/") + filename;
            runMap.Start();
            runMap.WaitForExit();
            runMap.Close();


            ExcelConnection2(excelfilename, execlsheetname);
            //Set Filename in Session for Download Purpose
            FileName2 = excelfilename;
            ImgFileName2 = userFileName;

            //Delete Image File 
            if (File.Exists(Server.MapPath("~/CApplication/") + filename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + filename);

            }

            string htmlfilename = filenameWithOutEx + ".html";
            // Delete html  File 
            if (File.Exists(Server.MapPath("~/CApplication/") + htmlfilename))
            {
                File.Delete(Server.MapPath("~/CApplication/") + htmlfilename);

            }
            string csvfilename = filenameWithOutEx + ".csv";
            // Show data to Grid
            if (File.Exists(Server.MapPath("~/CApplication/") + csvfilename))
            {
                DataTable csvdatatable = new DataTable();
                using (CsvReader csvData = new CsvReader(Server.MapPath("~/CApplication/" + csvfilename)))
                {
                    // set GridView to use DataTable returned from parser as the source
                    // for it's data. True is passed in to signify that file contains a
                    // header row which will name returned DataColumn's based on values
                    // read in from header row.

                    CsvDT2 = csvData.ReadIntoDataTable();
                    csvdatatable = csvData.ReadIntoDataTable();

                    // Get Color Tab 
                    SetColorTab2(csvdatatable);
                    // Get SubColor Tab 
                    SetSubColorTab2(csvdatatable);
                    // Get Color Brightness
                    SetColorBrightNess2(csvdatatable);
                    // Get Brightness Level
                    SetColorAreaPercentagetab2(csvdatatable);
                    // Get Color Attribute
                    SetColorAttributeTab2(csvdatatable);
                    // Get Attribute Families 
                    SetAttributeFamiliesTab2(csvdatatable);
                    // Get White Color Neutralization
                    SetWhiteColorNeutralisetab2(csvdatatable);
                    // Get Contributed Color
                    SetContributedColorTab2(csvdatatable);

                    trBtn2.Style.Add(HtmlTextWriterStyle.Display, "");
                    TabContainer2.Style.Add(HtmlTextWriterStyle.Display, "");
                } // dispose of parser

                // Write Csv File to Column
                using (CsvWriter csvwriter = new CsvWriter())
                {
                    csvwriter.WriteCsv(csvdatatable, Server.MapPath("~/CApplication/" + csvfilename));

                }
                CsvFileName2 = csvfilename;
                //byte[] filedate = File.ReadAllBytes(Server.MapPath("~/CApplication/" + csvfilename));
                //Session["Filedata"] = filedate;

                // Delete csv  File 
                if (File.Exists(Server.MapPath("~/CApplication/") + csvfilename))
                {
                    File.Delete(Server.MapPath("~/CApplication/") + csvfilename);

                }
                if (File.Exists(Server.MapPath("~/UpldImage/") + userFileName + "1"))
                {
                    File.Delete(Server.MapPath("~/UpldImage/") + userFileName + "1");
                }
                ImagePath2 = "~/UpldImage/" + userFileName;
                Image2.ImageUrl = "~/UpldImage/" + userFileName + "?uid=" + rndQuery.Next(0, 9999).ToString();
                Image2.Style.Add(HtmlTextWriterStyle.Display, "");
                LabelImageName2.Style.Add(HtmlTextWriterStyle.Display, "block");
                LabelImageName2.Text = userFileName;
                lblImgSize2.InnerText = getImageSize(Server.MapPath(ImagePath2));

                SuccesLabel2.Text = "Upload status: File uploaded!";

                btnViewDetail.Visible = true;
                //Panel2.Style.Add("display", "block");
                trUpload.Style[HtmlTextWriterStyle.Display] = "none";
                trAfterUpload.Style[HtmlTextWriterStyle.Display] = "";
                second = true;
            }
        }

        private string getImageSize(string filePath)
        {
            // find size of the file
            string[] sizes = { "B", "KB", "MB", "GB" };
            int s = 0;
            long fileSize = new FileInfo(filePath).Length;
            while (fileSize >= 1024)
            {
                s++;
                fileSize /= 1024;
            }
            //Old code
            //string fileSizeInfo = String.Format("( {0} {1} )", fileSize, sizes[s]);

            string fileSizeInfo = String.Format("{0} {1}", fileSize, sizes[s]);

            return fileSizeInfo;
        }

        public int InsertAdminReport(string fileName, decimal size)
        {
            string paymentTransactionId = null;
            string paymentDetails = null;
            bool? paymentStatus = null;

            //if its after payment
            if (!string.IsNullOrEmpty(Request.QueryString["txId"]))
            {
                paymentTransactionId = Request.QueryString["txId"];
                paymentDetails = Request.Url.PathAndQuery.Replace(Request.Url.AbsolutePath, "");
                paymentStatus = string.IsNullOrEmpty(Request.QueryString["ErrorCode"]);
            }
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters ={
                                          new SqlParameter("@PictureName",fileName),
                                          new SqlParameter("@Size",size),
                                          new SqlParameter("@Date",DateTime.Now),
                                          new SqlParameter("@PaymentTransactionId",paymentTransactionId),
                                          new SqlParameter("@PaymentDetails", paymentDetails),
                                          new SqlParameter("@PaymentStatus",paymentStatus)
                                          };
                SqlCommand cmd = SQLHelper.GetCommand(con, "InsertAdminReport", parameters);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                con.Close();
                DataTable dt = new DataTable();
                dt.Load(dr);
                if (dt.Rows.Count > 0)
                {
                    return Convert.ToInt32(dt.Rows[0]["Id"]);
                }
            }
            return 0;
        }

        public void SetColorTab(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            colordt.Columns.Add("Percentage");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage.ToString();
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Percentage", typeof(decimal));
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Percentage"] = GetPercentageofColor(color, colordt);
            }
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                if (color == "Transparent/White")
                {
                    row["Percentage"] = GetNeutralizedPercentageofColor(color, tempdt);
                    break;
                }
            }
            // Bind ColorGridView Of this Table
            tempdt.DefaultView.Sort = "Color";
            ColorDT = tempdt;


        }

        public void SetSubColorTab(DataTable csvdatatable)
        {
            // This is Create SubColor Table 
            DataTable subcolordatatable = new DataTable();
            subcolordatatable.Columns.Add("Sub-Color");
            subcolordatatable.Columns.Add("Percentage");
            subcolordatatable.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {
                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Sub Color Name from database
                string SubColor = GetSubcolorName(RCode, GCode, BCode);
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);

                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = subcolordatatable.NewRow();
                r["Sub-Color"] = SubColor;
                r["Percentage"] = totalPixcelPercentage.ToString();
                r["Color"] = Color;
                subcolordatatable.Rows.Add(r);

            }
            DataTable tempdt = subcolordatatable.DefaultView.ToTable(true, "Sub-Color");
            tempdt.Columns.Add("Percentage");
            tempdt.Columns.Add("Color");
            // Calculated SubColor Percentage of Picture

            //  Calculated SubColor Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string subcolor = row["Sub-Color"].ToString();
                row["Percentage"] = GetPercentageofSubColor(subcolor, subcolordatatable);
                row["Color"] = GetMainColorSubColor(subcolor, subcolordatatable);
            }
            // Bind ColorGridView Of this Table
            SubColorDetailsDT = tempdt;
            SubColorDeatilsGridView.DataSource = tempdt;
            SubColorDeatilsGridView.DataBind();


        }

        public void SetColorBrightNess(DataTable csvdatatable)
        {
            // This is Create SubColor Table 
            DataTable colorbrightnessdatatable = new DataTable();
            colorbrightnessdatatable.Columns.Add("Color");
            colorbrightnessdatatable.Columns.Add("Percentage");
            colorbrightnessdatatable.Columns.Add("Brightness");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                decimal brightness = Convert.ToDecimal(row["Column 11"].ToString());
                DataRow r = colorbrightnessdatatable.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage;
                r["Brightness"] = brightness;
                colorbrightnessdatatable.Rows.Add(r);

            }


            DataTable tempdt = colorbrightnessdatatable.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Brightness");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Brightness"] = GetBrightNesseofColor(color, colorbrightnessdatatable);
            }

            ColorBrightNessDT = tempdt;
            // Bind ColorGridView Of this Table
            ColorBrightNessGridView.DataSource = tempdt;
            ColorBrightNessGridView.DataBind();

        }

        public void SetColorAttributeTab(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");

            DataTable attributedt = new DataTable();
            attributedt.Columns.Add("Attribute");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string ColorName = row["Color"].ToString();
                List<string> listofattribute = GetColorAttributesByColorName(ColorName);
                foreach (string attribute in listofattribute)
                {
                    DataRow attributerow = attributedt.NewRow();
                    attributerow["Attribute"] = attribute;
                    attributedt.Rows.Add(attributerow);

                }
            }

            DataTable tempattributedt = attributedt.DefaultView.ToTable(true, "Attribute");
            tempattributedt.Columns.Add("Count", typeof(int));
            tempattributedt.Columns.Add("Color Area Percentage", typeof(double));
            tempattributedt.Columns.Add("Total OffSet Percentage", typeof(double));
            tempattributedt.Columns.Add("Calculated Weight After Offset", typeof(double));

            //iteration to fill color area percentage
            foreach (DataRow row in tempattributedt.Rows)
            {

                string attributename = row["Attribute"].ToString();
                row["Count"] = GetAttributeCount(attributename, attributedt);
                //Jayant Pawar
                int direction = GetAttributeDirection(attributename);
                DataTable brightnessLevel = ColorAreaPercentageDT as DataTable;
                double areaPercentage = 0;
                foreach (DataRow rw in brightnessLevel.Rows)
                {
                    if (rw["Attribute"].ToString().Equals(attributename))
                    {
                        //if (direction == 1)//1 is id of Good 
                        //{
                        areaPercentage += Convert.ToDouble(rw["Color Area Percentage"]);
                        //}
                        //else if (direction == 2)//2 is id of Bad
                        //{
                        //    areaPercentage -= Convert.ToDouble(rw["Color Area Percentage"]);
                        //}
                    }
                }
                row["Color Area Percentage"] = areaPercentage;
            }

            foreach (DataRow row in tempattributedt.Rows)
            {
                string attributename = row["Attribute"].ToString();
                DataTable Offset = GetOffsetAttributes(attributename);
                double areaPercentage = (double)row["Color Area Percentage"];
                double totalOffPercentage = 0;
                bool isOffsetActivate = false;
                if (Offset != null)
                {
                    isOffsetActivate = GetUseOffset();
                    if (isOffsetActivate)
                    {
                        foreach (DataRow dr in Offset.Rows)
                        {
                            string Attribute1 = dr["Attribute1"].ToString();
                            string Attribute2 = dr["Attribute2"].ToString();
                            string offAttribute = null;
                            if (Attribute1 != attributename)
                            {
                                offAttribute = Attribute1;
                            }
                            if (Attribute2 != attributename)
                            {
                                offAttribute = Attribute2;
                            }
                            DataRow[] drs = tempattributedt.Select("Attribute='" + offAttribute + "'");
                            if (drs.Length > 0)
                            {
                                totalOffPercentage += (double)drs[0]["Color Area Percentage"];
                            }
                        }
                    }
                }
                row["Total OffSet Percentage"] = totalOffPercentage;
                row["Calculated Weight After Offset"] = areaPercentage - totalOffPercentage;
            }
            // Bind ColorAttributeGridView Of this Table
            tempattributedt.DefaultView.Sort = "Count DESC";
            ColorAttributeDT = tempattributedt;
            ColorAttributeGridView.DataSource = tempattributedt;
            ColorAttributeGridView.DataBind();


        }

        //Jayant Pawar
        private DataTable GetOffsetAttributes(string attributename)
        {
            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Attribute", attributename) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetOffsetWithAttributeName", parameters);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                    return dt;
                return null;
            }
        }

        public void SetAttributeFamiliesTab(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");

            DataTable attributedt = new DataTable();
            attributedt.Columns.Add("Attribute");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string ColorName = row["Color"].ToString();
                List<string> listofattribute = GetColorAttributesByColorName(ColorName);
                foreach (string attribute in listofattribute)
                {
                    DataRow attributerow = attributedt.NewRow();
                    attributerow["Attribute"] = attribute;
                    attributedt.Rows.Add(attributerow);

                }
            }

            DataTable attributefamiliesdt = attributedt.DefaultView.ToTable(true, "Attribute");
            DataTable attributeXAttributefamiliesdt = new DataTable();
            attributeXAttributefamiliesdt.Columns.Add("Attribute");
            attributeXAttributefamiliesdt.Columns.Add("Attribute Families");

            foreach (DataRow row in attributefamiliesdt.Rows)
            {
                string AttributeName = row["Attribute"].ToString();
                DataTable AttributesFamiliesdt = GetAttributesFamiliesByAttributeName(AttributeName);
                if (AttributesFamiliesdt != null)
                {
                    foreach (DataRow familiesrow in AttributesFamiliesdt.Rows)
                    {
                        DataRow attributeXAttributefamiliesrow = attributeXAttributefamiliesdt.NewRow();
                        attributeXAttributefamiliesrow["Attribute"] = familiesrow["Attribute"];
                        attributeXAttributefamiliesrow["Attribute Families"] = familiesrow["Attribute Families"];
                        attributeXAttributefamiliesdt.Rows.Add(attributeXAttributefamiliesrow);
                    }

                }

            }

            DataTable attributeXFamailiesTempdt = attributeXAttributefamiliesdt.DefaultView.ToTable(true, "Attribute Families");

            attributeXFamailiesTempdt.Columns.Add("Attribute");
            attributeXFamailiesTempdt.Columns.Add("Count", Type.GetType("System.Int32"));
            attributeXFamailiesTempdt.Columns.Add("Percentage", Type.GetType("System.Double"));
            attributeXFamailiesTempdt.Columns.Add("WeightedPercentage", Type.GetType("System.Double"));
            List<WantedAttributeFamily> wantedFamilyList = new List<WantedAttributeFamily>();
            decimal wantedFamilyMark = 0;
            if (Session["wantedFamilyList"] == null)
            {
                string selectedAttributes = string.Empty;
                foreach (GridViewRow row in grdVwAttribute.Rows)
                {
                    CheckBox chk = row.FindControl("chk") as CheckBox;
                    if (chk.Checked)
                    {
                        DropDownList ddlAppearance = row.FindControl("ddlAppearance") as DropDownList;
                        Label lblAttributeFamily = row.FindControl("lblAttributeFamily") as Label;
                        WantedAttributeFamily wantedFamily = new WantedAttributeFamily();
                        wantedFamily.AttributeFamily = lblAttributeFamily.Text;
                        wantedFamily.AppearanceValue = Convert.ToInt32(ddlAppearance.SelectedValue);
                        selectedAttributes += lblAttributeFamily.Text + ", ";
                        wantedFamilyList.Add(wantedFamily);
                    }
                }
                if (selectedAttributes.Length > 0)
                    selectedAttributes = selectedAttributes.Substring(0, selectedAttributes.Length - 2);
                Session["wantedFamilyList"] = wantedFamilyList;
                if (wantedFamilyList.Count > 0)
                {
                    lblSelected.Visible = true;
                    lblSelected.Text = string.Format(lblSelected.Text, selectedAttributes);
                }
            }
            else
            {
                wantedFamilyList = Session["wantedFamilyList"] as List<WantedAttributeFamily>;

            }

            ////List to hold values of rowindex to delete
            //List<int> lstDeleteRow = new List<int>();

            foreach (DataRow row in attributeXFamailiesTempdt.Rows)
            {
                string AttributeFamilies = row["Attribute Families"].ToString();
                DataTable AttributeList = GetAttribute(attributeXAttributefamiliesdt, AttributeFamilies);
                string attributestr = string.Empty;
                int AttributeCount = 0;
                double percentage = 0;
                DataTable ColorAttributedatatable = ColorAttributeDT as DataTable;
                foreach (DataRow dr in AttributeList.Rows)
                {
                    string atrbte = dr["Attribute"].ToString();
                    double totalofPercentage = GetColorTotalFamilyPercentage(ColorAttributedatatable, AttributeList);
                    double colorPercentage = GetColorPercentageofAttribute(ColorAttributedatatable, atrbte);
                    double attributePercentage = 0;
                    if (totalofPercentage > 0)
                    {
                        attributePercentage = (colorPercentage / totalofPercentage) * 100;
                    }
                    dr["Percentage"] = attributePercentage;
                }
                AttributeList.DefaultView.Sort = "Percentage DESC";
                AttributeList = AttributeList.DefaultView.ToTable();

                foreach (DataRow dr in AttributeList.Rows)
                {
                    if (Math.Round(Convert.ToDouble(dr["Percentage"])) > 0)
                    {
                        AttributeCount++;
                        attributestr = attributestr + dr["Attribute"] + " " + String.Format("{0:00.00}", Math.Round(Convert.ToDouble(dr["Percentage"]), 2)) + "% </br>";
                    }

                    foreach (DataRow rw in ColorAttributedatatable.Rows)
                    {
                        if (rw["Attribute"].ToString().Equals(dr["Attribute"]))
                        {

                            percentage += Convert.ToDouble(rw["Color Area Percentage"]);
                        }
                    }

                }

                row["Attribute Families"] = row["Attribute Families"];
                row["Attribute"] = attributestr;
                row["Count"] = AttributeCount;
                row["Percentage"] = percentage;
                //if (row["MinPercentage"] != DBNull.Value && percentage < Convert.ToDouble(row["MinPercentage"]))
                //    lstDeleteRow.Add(attributeXFamailiesTempdt.Rows.IndexOf(row));

            }

            //foreach (int item in lstDeleteRow)
            //{
            //    attributeXFamailiesTempdt.Rows.RemoveAt(item);
            //}

            attributeXFamailiesTempdt.DefaultView.Sort = "Percentage DESC";
            int? maxAttributeFamilies = GetMaxAttributeFamilies();
            if (maxAttributeFamilies != null)
                attributeXFamailiesTempdt = GetTopRecords(attributeXFamailiesTempdt, Convert.ToInt32(maxAttributeFamilies));

            //Calculate weighted percentage
            attributeXFamailiesTempdt = CalculatedWeightedAttributeFamily(attributeXFamailiesTempdt);

            //querystring value to be sent to pie chart api
            string attributeNamesForPieChart = string.Empty;
            string attributePercentagesForPieChart = "t:";
            decimal total = 0;
            foreach (DataRow row in attributeXFamailiesTempdt.Rows)
            {
                string AttributeFamilies = row["Attribute Families"].ToString();
                if (wantedFamilyList.Count > 0)
                {
                    foreach (WantedAttributeFamily wantedFamily in wantedFamilyList)
                    {
                        if (AttributeFamilies == wantedFamily.AttributeFamily)
                        {

                            if (row["WeightedPercentage"] != DBNull.Value)
                            {
                                wantedFamilyMark = wantedFamilyMark + Convert.ToDecimal((Convert.ToDouble(row["WeightedPercentage"])) * wantedFamily.AppearanceValue);
                            }
                        }
                    }
                    wantedFamilyMark = Math.Round(wantedFamilyMark, 2);
                    WantedFamilyMark = wantedFamilyMark;
                }
                else
                {
                    if (WantedFamilyMark != null)
                        wantedFamilyMark = (decimal)WantedFamilyMark;
                }

                if (row["WeightedPercentage"] != DBNull.Value)
                {
                    total += Convert.ToDecimal(row["WeightedPercentage"]);
                    attributeNamesForPieChart += AttributeFamilies + " " + row["WeightedPercentage"].ToString() + "%|";
                    attributePercentagesForPieChart += row["WeightedPercentage"].ToString() + ",";
                }
            }
            decimal other = 100 - total;
            if (other > 0)
            {
                attributeNamesForPieChart += "Others" + " " + other.ToString() + "%|";
                attributePercentagesForPieChart += other.ToString() + ",";
            }
            if (Session["wantedFamilyList"] != null)
                lblWantedFamilyMark.Text = "Marks of wanted families in the picture: " + wantedFamilyMark.ToString();
            string url = string.Empty;
            //assigning piechart url to image
            if (ImgFileName2 != null)
            {
                if (!string.IsNullOrEmpty(attributePercentagesForPieChart) && attributePercentagesForPieChart.Length > 2)
                    url = "https://chart.googleapis.com/chart?chs=400x100&chd=" + attributePercentagesForPieChart.Substring(0, attributePercentagesForPieChart.Length - 1)
                         + "&cht=p3&chl=" + attributeNamesForPieChart.Substring(0, attributeNamesForPieChart.Length - 1) + "&chco=9568a3";
                pnlPieImg1.Style[HtmlTextWriterStyle.Display] = "block";
                pnlPieImg1.Attributes["style"] += "float: left; width: 50%;";
            }
            else
            {
                if (!string.IsNullOrEmpty(attributePercentagesForPieChart) && attributePercentagesForPieChart.Length > 2)
                    url = "https://chart.googleapis.com/chart?chs=650x200&chd=" + attributePercentagesForPieChart.Substring(0, attributePercentagesForPieChart.Length - 1)
                                   + "&cht=p3&chl=" + attributeNamesForPieChart.Substring(0, attributeNamesForPieChart.Length - 1) + "&chco=9568a3";
                pnlPieImg1.Style[HtmlTextWriterStyle.Display] = "block";
            }

            PieFileName = ImgFileName.Substring(0, ImgFileName.IndexOf(".") + 1) + "pieChart1.png";

            if (!string.IsNullOrEmpty(url))
            {
                SaveImageFromUrl("~/UpldImage/" + PieFileName, url);
                imgPieChart1.ImageUrl = "~/UpldImage/" + PieFileName + "?uid=" + rndQuery.Next(0, 9999).ToString();
            }

            AttributeFamiliesDT = attributeXFamailiesTempdt;
            AttributeFamiliesGridView.DataSource = attributeXFamailiesTempdt;
            AttributeFamiliesGridView.DataBind();
        }

        private int? GetMaxAttributeFamilies()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            // Get Reduce White Color Percentage
            int? maxAttributeFamilies = null;

            if (ds.Tables[0].Rows[0]["MaximumAttributeFamilies"] != DBNull.Value)
                maxAttributeFamilies = Convert.ToInt32(ds.Tables[0].Rows[0]["MaximumAttributeFamilies"]);

            return maxAttributeFamilies;
        }

        private decimal? GetMinAttributeFamilyPercentage()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            // Get Reduce White Color Percentage
            decimal? MinimumPercentage = null;

            if (ds.Tables[0].Rows[0]["MinimumPercentage"] != DBNull.Value)
                MinimumPercentage = Convert.ToDecimal(ds.Tables[0].Rows[0]["MinimumPercentage"]);

            return MinimumPercentage;
        }

        //Shravankumar 
        /// <summary>
        /// Get Color Percentage ColorAttributedatatable
        /// </summary>
        /// <param name="ColorAttributedatatable"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        public double GetColorPercentageofAttribute(DataTable ColorAttributedatatable, string attribute)
        {
            double percentageofAttribute = 0;
            if (ColorAttributedatatable != null)
            {
                foreach (DataRow row in ColorAttributedatatable.Rows)
                {
                    if (row["Attribute"].ToString().Equals(attribute))
                    {
                        percentageofAttribute = Convert.ToDouble(row["Color Area Percentage"]);
                        return percentageofAttribute;
                    }
                }

            }
            return percentageofAttribute;
        }
        //Shravankumar 
        /// <summary>
        /// this method for calculated Total of attribute Percentage
        /// </summary>
        /// <param name="ColorAttributedatatable"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        public double GetColorTotalFamilyPercentage(DataTable ColorAttributedatatable, DataTable AttributeList)
        {
            double totalofPercentage = 0;
            if (ColorAttributedatatable != null)
            {
                foreach (DataRow attribute in AttributeList.Rows)
                {
                    foreach (DataRow row in ColorAttributedatatable.Rows)
                    {

                        if (row["Attribute"].ToString().Equals(attribute["Attribute"]) && Convert.ToDouble(row["Color Area Percentage"]) > 0)
                        {
                            totalofPercentage += Convert.ToDouble(row["Color Area Percentage"]);
                        }
                    }
                }

                return totalofPercentage;
            }
            return totalofPercentage;


        }
        //Shravankumar 
        /// <summary>
        /// This method Accept Parameter Datatable and Calculated WeightedPercentage for Attribute family
        /// </summary>
        /// <param name="attributeXFamailiesTempdt">DataTable</param>
        /// <returns>DataTable</returns>
        public DataTable CalculatedWeightedAttributeFamily(DataTable attributeXFamailiesTempdt)
        {
            //List to hold values of rowindex to delete
            List<int> lstDeleteRow = new List<int>();
            decimal? MinimumPercentage = GetMinAttributeFamilyPercentage();

            if (attributeXFamailiesTempdt != null)
            {
                double totalofWeightPercentage = GetTotalofWeightedAttributeFamilyPercentage(attributeXFamailiesTempdt);

                foreach (DataRow row in attributeXFamailiesTempdt.Rows)
                {
                    if (Convert.ToDouble(row["Percentage"]) > 0 && totalofWeightPercentage > 0)
                    {
                        double percentage = Math.Round((Convert.ToDouble(row["Percentage"]) / totalofWeightPercentage) * 100, 2);
                        row["WeightedPercentage"] = percentage;
                        if (MinimumPercentage != null && percentage <= Convert.ToDouble(MinimumPercentage))
                            lstDeleteRow.Add(attributeXFamailiesTempdt.Rows.IndexOf(row));
                    }
                }

                //to calculate the row correctly
                int count = 0;
                foreach (int item in lstDeleteRow)
                {
                    attributeXFamailiesTempdt.Rows.RemoveAt(item - count);
                    count++;
                }

            }
            return attributeXFamailiesTempdt;
        }
        //Shravankumar Get Total of Weighted Percentage of AttributeFamily 
        /// <summary>
        /// Accept DataTable attributeXFamailiesTempdt return totalofWeightPercentage
        /// </summary>
        /// <param name="attributeXFamailiesTempdt"></param>
        /// <returns></returns>
        public double GetTotalofWeightedAttributeFamilyPercentage(DataTable attributeXFamailiesTempdt)
        {
            double totalofWeightPercentage = 0;
            if (attributeXFamailiesTempdt != null)
            {
                foreach (DataRow row in attributeXFamailiesTempdt.Rows)
                {
                    if (Convert.ToDouble(row["Percentage"]) > 0)
                    {
                        totalofWeightPercentage += Convert.ToDouble(row["Percentage"]);
                    }
                }

                return totalofWeightPercentage;
            }
            return totalofWeightPercentage;


        }

        //Jayant Pawar
        private void SetWhiteColorNeutralisetab(DataTable csvdatatable)
        {

            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            colordt.Columns.Add("Percentage");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                if (Color == "Transparent/White")
                {
                    r["Color"] = Color;
                    r["Percentage"] = totalPixcelPercentage.ToString();

                    colordt.Rows.Add(r);
                }

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Real Percentage");
            tempdt.Columns.Add("Neutralized Percentage");

            lblWhiteNeuMessage.Visible = true;
            if (tempdt.Rows.Count < 1)
                lblWhiteNeuMessage.Text = "White color neutralization is not activated.";

            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Real Percentage"] = GetPercentageofColor(color, colordt);
                row["Neutralized Percentage"] = GetNeutralizedPercentageofColor(color, colordt);

                if (Convert.ToDouble(row["Real Percentage"]) > Convert.ToDouble(row["Neutralized Percentage"]))
                    lblWhiteNeuMessage.Text = "White color neutralization (" + row["Neutralized Percentage"].ToString() + ") is activated.";
                else
                    lblWhiteNeuMessage.Text = "White color neutralization is not activated.";

            }
            // Bind ColorGridView Of this Table

            WhiteColorNeutralization = tempdt;
            WhiteColorNeutralizationGridView.DataSource = tempdt;
            WhiteColorNeutralizationGridView.DataBind();

        }
        //Jayant Pawar
        private void SetColorAreaPercentagetab(DataTable csvdatatable)
        {
            DataTable colorbrightnessdatatable = new DataTable();
            colorbrightnessdatatable.Columns.Add("Color");
            colorbrightnessdatatable.Columns.Add("Percentage");
            colorbrightnessdatatable.Columns.Add("Brightness");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colorbrightnessdatatable.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage;
                r["Brightness"] = Convert.ToDecimal(row["Column 11"].ToString());
                colorbrightnessdatatable.Rows.Add(r);

            }


            DataTable brightnessTable = colorbrightnessdatatable.DefaultView.ToTable(true, "Color");

            DataTable resultDT = new DataTable();
            resultDT.Columns.Add("Color");
            resultDT.Columns.Add("Attribute");
            resultDT.Columns.Add("Brightness");
            resultDT.Columns.Add("Calculated Brightness Level");
            resultDT.Columns.Add("Color Area Percentage");

            // Calculated Color Brightness of Picture
            foreach (DataRow row in brightnessTable.Rows)
            {
                string color = row["Color"].ToString();
                double colorPercentage = 0;

                //find color percentage from  ColorDT
                DataTable table = (DataTable)ColorDT;
                DataRow colorRow = table.Select("Color='" + color + "'")[0];
                colorPercentage = double.Parse(colorRow["Percentage"].ToString());

                double brightness = Convert.ToDouble(GetBrightNesseofColor(color, colorbrightnessdatatable));
                DataTable colorAttribute = GetColorAttributes(color);

                if (colorAttribute != null)
                {
                    foreach (DataRow rw in colorAttribute.Rows)
                    {
                        DataRow dr = resultDT.NewRow();
                        double actualColorPercentage = colorPercentage;

                        double fromValue, toValue, maxValue, dominantValue = 1, ColorAreaPercentage = 0, brightnessLevel = 0; ;
                        fromValue = Convert.ToDouble(rw["BrightnessLevelFrom"]);
                        toValue = Convert.ToDouble(rw["BrightnessLevelTo"]);
                        maxValue = Convert.ToDouble(rw["BrightnessMaxValue"]);
                        if (fromValue.Equals(0) && toValue.Equals(0) && maxValue.Equals(0))
                        {
                            toValue = 1;
                            maxValue = 0.5;
                        }
                        dr["Color"] = color;



                        dr["Attribute"] = rw["Attribute"];
                        dr["Brightness"] = brightness;
                        if (brightness >= fromValue && brightness <= toValue)
                        {
                            if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(1)
                                || fromValue.Equals(0) && toValue.Equals(0.5) && maxValue.Equals(0.5)
                                  || fromValue.Equals(0.5) && toValue.Equals(1) && maxValue.Equals(1))
                            {
                                brightnessLevel = (brightness - fromValue) / (toValue - fromValue);
                            }
                            else if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(0)
                                    || fromValue.Equals(0) && toValue.Equals(0.5) && maxValue.Equals(0)
                                      || fromValue.Equals(0.5) && toValue.Equals(1) && maxValue.Equals(0.5))
                            {
                                brightnessLevel = (toValue - brightness) / (toValue - fromValue);
                            }
                            else if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(0.5))
                            {

                                brightnessLevel = (0.5 - Math.Abs(0.5 - brightness)) / 0.5;
                            }

                            if (Convert.ToBoolean(rw["IsDominant"]))
                            {
                                dominantValue = getDominantValue();

                                //increase color percentage for dominant
                                actualColorPercentage = colorPercentage * dominantValue;
                            }

                            if (brightnessLevel < 0)
                                brightnessLevel = 0;

                            //changing as per latese discussion with client -- paresh
                            //ColorAreaPercentage = dominantValue * (1 + brightnessLevel);
                            ColorAreaPercentage = actualColorPercentage * (1 + brightnessLevel);
                        }


                        dr["Calculated Brightness Level"] = brightnessLevel;
                        dr["Color Area Percentage"] = ColorAreaPercentage;
                        resultDT.Rows.Add(dr);
                    }
                }
            }

            ColorAreaPercentageDT = resultDT;
            BrightnesLevelGridView.DataSource = resultDT;
            BrightnesLevelGridView.DataBind();
        }
        //Jayant Pawar
        private void SetContributedColorTab(DataTable csvdatatable)
        {
            DataTable ColorAttributedatatable = ColorAttributeDT as DataTable;
            ColorAttributedatatable.DefaultView.Sort = "Color Area Percentage Desc";
            ColorAttributedatatable = ColorAttributedatatable.DefaultView.ToTable();
            DataTable Colordatatable = ColorDT as DataTable;
            int AttributeId = GetAttributeId(ColorAttributedatatable.Rows[0]["Attribute"].ToString());
            DataTable ColorsInAttribute = GetColorsByAttributes(AttributeId);
            DataTable result = new DataTable();
            result.Columns.Add("Color");
            result.Columns.Add("Percentage", typeof(decimal));
            string star = "<font style=\"color: red; font-weight: bold;\">*</font>";
            foreach (DataRow dr in ColorsInAttribute.Rows)
            {
                foreach (DataRow colordr in Colordatatable.Rows)
                {
                    if (dr["Color"].ToString() == colordr["Color"].ToString().Replace(star, string.Empty))
                    {
                        DataRow resultRow = result.NewRow();
                        resultRow["Color"] = colordr["Color"];
                        resultRow["Percentage"] = Convert.ToDecimal(colordr["Percentage"]);
                        result.Rows.Add(resultRow);
                    }
                }
            }
            result.DefaultView.Sort = "Percentage DESC";
            result = result.DefaultView.ToTable();
            //Old Coding to add * to color
            //foreach (DataRow colordr in Colordatatable.Rows)
            //{
            //    if (colordr["Color"].ToString().Replace(star, string.Empty) == result.Rows[0]["Color"].ToString())
            //    {
            //        colordr["Color"] = colordr["Color"].ToString() + star;
            //    }
            //    else
            //    {
            //        colordr["Color"] = colordr["Color"].ToString().Replace(star, string.Empty);
            //    }
            //}
            lblContributeColor1.Text = string.Format(lblContributeColor1.Text, result.Rows[0]["Color"].ToString());
            ColorDT = Colordatatable;
            ColorGridView.DataSource = Colordatatable;
            ColorGridView.DataBind();
        }
        //Jayant Pawar
        public DataTable GetColorAttributes(string color)
        {

            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@ColorName", color) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetSearchByColorsAttributeSelect", parameters);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                    return dt;
                return null;
            }
        }
        //Jayant Pawar
        public DataTable GetColorsByAttributes(int AttributeId)
        {

            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@AttributeId", AttributeId) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetSearchByColorsAttributeSelect", parameters);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                    return dt;
                return null;
            }
        }
        //Jayant Pawar
        public int GetAttributeId(string Description)
        {
            // This Function Check Record in Attribute Table For Dublicate Description Name Exist or Not
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Description", Description) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckDescriptionExistinAttribute", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                return (int)dr["Id"];
            }

            return 0;

        }
        //Jayant Pawar
        public double getDominantValue()
        {
            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {

                SqlParameter[] parameter = { new SqlParameter("@Id", null) };
                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameter);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                    return Convert.ToDouble(dt.Rows[0]["DominantAttributesFactor"]);
                return 1;
            }
        }

        public List<string> GetColorAttributesByColorName(string ColorName)
        {
            List<string> listofattribute = new List<string>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@ColorName", ColorName) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetColorAttributesByColorName", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                // Get Attribute Name
                string AttributeName = dr["Description"].ToString();
                listofattribute.Add(AttributeName);

            }
            return listofattribute;

        }

        public DataTable GetAttribute(DataTable attributeXFamailiesdt, string AttributeFamilies)
        {

            DataTable AttributeList = new DataTable();
            AttributeList.Columns.Add("Attribute");
            AttributeList.Columns.Add("Percentage", typeof(double));

            if (attributeXFamailiesdt != null)
            {
                foreach (DataRow row in attributeXFamailiesdt.Rows)
                {
                    if (row["Attribute Families"].ToString() == AttributeFamilies)
                    {
                        DataRow dr = AttributeList.NewRow();
                        dr["Attribute"] = row["Attribute"].ToString();
                        AttributeList.Rows.Add(dr);
                    }
                }
            }
            return AttributeList;
        }

        public DataTable GetAttributesFamiliesByAttributeName(string AttributeName)
        {

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@AttributeName", AttributeName) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetAttributesFamiliesByAttributeName", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }
            return ds.Tables[0];
        }

        public decimal GetTotalArea(DataTable dt)
        {
            // get Total Area in Picture
            decimal totalArea = 0;
            foreach (DataRow row in dt.Rows)
            {
                totalArea += Convert.ToDecimal(row["Percentage"]);
            }
            return totalArea;
        }

        public string GetPercentageofColor(string color, DataTable dt)
        {
            // This function Calculated How many percentage of Color in That Picture
            decimal totalPercentage = 0;

            foreach (DataRow row in dt.Rows)
            {
                if (row["Color"].ToString() == color)
                {
                    totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());

                    /*List<string> listofattribute = GetColorAttributesByColorName(color);

                    foreach (string attribute in listofattribute)
                    {
                        int direction = GetAttributeDirection(attribute);
                        if (direction==1)//1 for good
                        {
                            totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());
                        }
                        else if (direction == 2)//2 for bad
                        {
                            totalPercentage -= Convert.ToDecimal(row["Percentage"].ToString());
                        }
                    }*/
                }


            }
            if (totalPercentage > 0)
            {
                return string.Format("{0:0.00}", totalPercentage);
            }
            else
            {
                return "0";
            }

        }

        //Jayant Pawar
        private int GetAttributeDirection(string attribute)
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Description", attribute) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetAttributeDirection", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                // Get Attribute Name
                int Direction = Convert.ToInt32(dr["Direction"]);
                return Direction;
            }
            return 0;
        }

        //Jayant Pawar
        public string GetNeutralizedPercentageofColor(string color, DataTable dt)
        {
            // This function Calculated How many percentage of Color in That Picture
            decimal totalPercentage = 0;

            foreach (DataRow row in dt.Rows)
            {
                if (row["Color"].ToString() == color)
                {
                    totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());

                    /*List<string> listofattribute = GetColorAttributesByColorName(color);

                    foreach (string attribute in listofattribute)
                    {
                        int direction = GetAttributeDirection(attribute);
                        if (direction==1)//1 for good
                        {
                            totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());
                        }
                        else if (direction == 2)//2 for bad
                        {
                            totalPercentage -= Convert.ToDecimal(row["Percentage"].ToString());
                        }
                    }*/
                }


            }
            decimal MaxWhiteColorPercentage = GetMaxWhiteColorPercentage();
            decimal ReduceWhiteColorPercentage = GetReduceWhiteColorPercentage();
            if (totalPercentage > MaxWhiteColorPercentage && ReduceWhiteColorPercentage > 0)
            {
                // changed by paresh to reduce the percentage by white color neutralization
                totalPercentage -= (totalPercentage * (ReduceWhiteColorPercentage / 100));
            }
            if (totalPercentage > 0)
            {
                return string.Format("{0:0.00}", totalPercentage);
            }
            else
            {
                return "0";
            }
        }

        private decimal GetReduceWhiteColorPercentage()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                // Get Reduce White Color Percentage
                decimal ReduceWhiteColorPercentage = Convert.ToDecimal(dr["ResultPercentage"]);
                return ReduceWhiteColorPercentage;
            }
            return 0;
        }

        private string GetCommonMessage()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //return CommonMessage
                return dr["CommonMessage"].ToString();
            }
            return string.Empty;
        }

        private decimal GetMaxWhiteColorPercentage()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                // Get Attribute Name
                decimal MaxWhiteColorPercentage = Convert.ToDecimal(dr["ColorPercentage"]);
                return MaxWhiteColorPercentage;
            }
            return 0;
        }

        private bool GetUseOffset()
        {
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Id", null) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            if (ds.Tables[0].Rows.Count > 0)
            {
                // Get Attribute Name
                bool UseOffset = Convert.ToBoolean(ds.Tables[0].Rows[0]["UseOffset"]);
                return UseOffset;
            }
            return false;
        }

        public string GetAttributeCount(string attribute, DataTable dt)
        {
            // This function Calculated How many Attribute in Attribute Table.
            int Count = 0;

            foreach (DataRow row in dt.Rows)
            {
                if (row["Attribute"].ToString() == attribute)
                {
                    Count++;
                }


            }
            return Count.ToString();

        }

        public string GetBrightNesseofColor(string color, DataTable dt)
        {
            // This function Calculated How many percentage of Color in That Picture
            decimal totalPercentage = 0;
            decimal totalBrightNess = 0;
            decimal totalamt = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (row["Color"].ToString() == color)
                {
                    totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());
                    totalBrightNess += Convert.ToDecimal(row["Brightness"].ToString());
                    totalamt += (Convert.ToDecimal(row["Percentage"].ToString()) * Convert.ToDecimal(row["Brightness"].ToString()));
                }


            }
            if (totalamt > 0 && totalPercentage > 0)
            {
                decimal mainBrightness = totalamt / totalPercentage;
                return mainBrightness.ToString();
            }
            else
            {
                return "0";
            }

        }

        public string GetMainColorSubColor(string subcolor, DataTable dt)
        {
            string Color = string.Empty;
            // This function Calculated How many percentage of Sub Color in That Picture
            foreach (DataRow row in dt.Rows)
            {
                if (row["Sub-Color"].ToString() == subcolor)
                {
                    Color = row["Color"].ToString();
                    return Color;
                }
            }
            return Color;

        }

        public string GetPercentageofSubColor(string subcolor, DataTable dt)
        {
            // This function Calculated How many percentage of Sub Color in That Picture
            decimal totalPercentage = 0;

            foreach (DataRow row in dt.Rows)
            {
                if (row["Sub-Color"].ToString() == subcolor)
                {
                    totalPercentage += Convert.ToDecimal(row["Percentage"].ToString());
                }


            }
            if (totalPercentage > 0)
            {
                return string.Format("{0:0.00}", totalPercentage);
            }
            else
            {
                return "0";
            }

        }

        public string GetcolorsinSubcolor(int RCode, int GCode, int BCode)
        {
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters ={
                                            new SqlParameter("@RCode",RCode),
                                            new SqlParameter("@GCode",GCode),
                                            new SqlParameter("@BCode",BCode)};
                SqlCommand cmd = SQLHelper.GetCommand(con, "GetcolorsinSubcolor", parameters);
                con.Open();
                string Color = Convert.ToString(cmd.ExecuteScalar());
                con.Close();
                if (Color != string.Empty)
                {

                    return Color;
                }
                else
                {
                    return "Unknown Color";

                }
            }
        }

        public string GetSubcolorName(int RCode, int GCode, int BCode)
        {
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters ={
                                            new SqlParameter("@RCode",RCode),
                                            new SqlParameter("@GCode",GCode),
                                            new SqlParameter("@BCode",BCode)};
                SqlCommand cmd = SQLHelper.GetCommand(con, "GetSubcolorName", parameters);
                con.Open();
                string SubColor = Convert.ToString(cmd.ExecuteScalar());
                con.Close();
                if (SubColor != string.Empty)
                {

                    return SubColor;
                }
                else
                {
                    return "Unknown Color";

                }
            }
        }

        protected void ExcelConnection(string filename, string SheetName)
        {
            //// This Functon is read csv file and Data set  to Grid View

            DataTable datatable = new DataTable();

            // declare csv parser passing in path to file
            using (CsvReader csvData = new CsvReader(Server.MapPath("~/CApplication/" + filename)))
            {
                // set GridView to use DataTable returned from parser as the source
                // for it's data. True is passed in to signify that file contains a
                // header row which will name returned DataColumn's based on values
                // read in from header row.
                datatable = csvData.ReadIntoDataTable();
                SetCSV(datatable);

            } // dispose of parser




        }

        public void SetCSV(DataTable csvdatatable)
        {
            CsvDT = csvdatatable;
            ShowFileGridView.DataSource = csvdatatable;
            ShowFileGridView.DataBind();

        }

        public void DeleteCsvFile()
        {

            if (FileName != null)
            {
                if (FileName.ToString() != string.Empty)
                {
                    string filename = FileName.ToString();

                    if (File.Exists(Server.MapPath("~/CApplication/") + filename))
                    {
                        FileName = null;
                        //Delete file 
                        File.Delete(Server.MapPath("~/CApplication/") + filename);
                    }
                }

            }

        }

        protected void DownloadButton_Click(object sender, EventArgs e)
        {
            try
            {
                modalPage.Style[HtmlTextWriterStyle.Visibility] = "hidden";
                //if (FileName != null && Session["Filedata"] != null)
                if (FileName != null)
                {
                    if (FileName.ToString() != string.Empty)
                    {
                        string filename = FileName.ToString().Replace(".csv", ".xls");
                        // byte[] Filedata = (byte[])Session["Filedata"];
                        //// Download .csv file
                        //DownLoadCSV(filename, Filedata);// Old Method to download CSV file
                        DownloadXLS(filename);
                    }
                    else
                    {

                        ErrorLabel.Text = "Please upload Image File";
                    }
                }
                else
                {

                    ErrorLabel.Text = "Please upload Image File";

                }
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        private void DownloadXLS(string filename)
        {
            const string m_Http_Attachment = "attachment;filename=";
            const string m_Http_Content = "content-disposition";

            HttpResponse m_Response = HttpContext.Current.Response;

            m_Response.Clear();
            m_Response.ClearContent();
            m_Response.ClearHeaders();
            m_Response.Buffer = true;

            m_Response.AddHeader(m_Http_Content, m_Http_Attachment + filename);
            m_Response.ContentEncoding = Encoding.UTF8;
            m_Response.Cache.SetCacheability(HttpCacheability.NoCache);

            StringWriter m_StringWriter = new StringWriter();
            HtmlTextWriter m_HtmlWriter = new HtmlTextWriter(m_StringWriter);

            ShowFileGridView.AllowPaging = false;
            ShowFileGridView.HeaderStyle.Font.Bold = true;

            DataTable csvdatatable = CsvDT as DataTable;
            ShowFileGridView.DataSource = csvdatatable;
            ShowFileGridView.DataBind();
            ClearControls(ShowFileGridView);
            ShowFileGridView.RenderControl(m_HtmlWriter);

            string m_gridViewText = m_StringWriter.ToString();

            m_Response.ContentType = "application/vnd.ms-excel";
            m_Response.Write(m_gridViewText);
            m_Response.End();
        }


        protected void DownLoadCSV(string filename, byte[] Filedata)
        {
            // This is file download code for .csv file
            string attachment = "attachment; filename=" + filename;
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "text/csv";
            Response.AddHeader("Pragma", "public");
            // Write Binay Data to response
            Response.BinaryWrite(Filedata);
            Response.End();
            //  Code to export the gridView to Excel File.
        }

        private static void ClearControls(Control control)
        {
            for (int index = control.Controls.Count - 1; index >= 0; index--)
            {
                ClearControls(control.Controls[index]);
            }

            if (!(control is TableCell))
            {
                if (control.GetType().GetProperty("SelectedItem") != null)
                {
                    LiteralControl m_Literal = new LiteralControl();
                    control.Parent.Controls.Add(m_Literal);

                    m_Literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
                    control.Parent.Controls.Remove(control);
                }
                else
                {
                    if (control.GetType().GetProperty("Text") != null)
                    {
                        LiteralControl m_Literal = new LiteralControl();
                        control.Parent.Controls.Add(m_Literal);
                        m_Literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                        control.Parent.Controls.Remove(control);
                    }
                }
            }
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }

            return newSortDirection;
        }

        protected void ShowFileGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = CsvDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["CSVLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["CSVLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["CSVLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["CSVLastSortExpression"] = e.SortExpression;
                    ViewState["CSVLastSortDirection"] = sSortDirection;

                    CsvDT = dataView.Table;


                    ShowFileGridView.DataSource = dataView;
                    ShowFileGridView.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void ColorGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["ColorLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["ColorLastSortExpression"] = e.SortExpression;
                    ViewState["ColorLastSortDirection"] = sSortDirection;

                    ColorDT = dataView.Table;


                    ColorGridView.DataSource = dataView;
                    ColorGridView.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();

            }
        }

        protected void SubColorDeatilsGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = SubColorDetailsDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["SubColorDeatilsLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["SubColorDeatilsLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["SubColorDeatilsLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["SubColorDeatilsLastSortExpression"] = e.SortExpression;
                    ViewState["SubColorDeatilsLastSortDirection"] = sSortDirection;

                    SubColorDetailsDT = dataView.Table;

                    SubColorDeatilsGridView.DataSource = dataView;
                    SubColorDeatilsGridView.DataBind();
                }

            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();

            }
        }

        protected void ColorBrightNessGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorBrightNessDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["ColorBrightNessLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorBrightNessLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorBrightNessLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["ColorBrightNessLastSortExpression"] = e.SortExpression;
                    ViewState["ColorBrightNessLastSortDirection"] = sSortDirection;

                    ColorBrightNessDT = dataView.Table;
                    ColorBrightNessGridView.DataSource = dataView;
                    ColorBrightNessGridView.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();

            }
        }

        protected void ColorAttributeGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorAttributeDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);

                    string sSortDirection = string.Empty;

                    if (ViewState["ColorAttributeLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorAttributeLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorAttributeLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;
                    ViewState["ColorAttributeLastSortExpression"] = e.SortExpression;
                    ViewState["ColorAttributeLastSortDirection"] = sSortDirection;

                    ColorAttributeDT = dataView.Table;
                    ColorAttributeGridView.DataSource = dataView;
                    ColorAttributeGridView.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();

            }
        }

        protected void AttributeFamiliesGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = AttributeFamiliesDT as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);

                    string sSortDirection = string.Empty;

                    if (ViewState["AttributeFamiliesLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["AttributeFamiliesLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["AttributeFamiliesLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;
                    ViewState["AttributeFamiliesLastSortExpression"] = e.SortExpression;
                    ViewState["AttributeFamiliesLastSortDirection"] = sSortDirection;

                    AttributeFamiliesDT = dataView.Table;
                    AttributeFamiliesGridView.DataSource = dataView;
                    AttributeFamiliesGridView.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();

            }


        }

        protected void WebFileButton_Click(object sender, EventArgs e)
        {
            if (CsvDT2 != null && CsvDT2.Rows.Count != 0)
            {
                downloadBoth();
            }
            else
            {
                Session["ClientID"] = "1";
                if (Request.QueryString["id"] != null)
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?download=true&id=" + Request.QueryString["id"].ToString());
                }
                else
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?download=true");
                }
            }
        }

        protected void ViewHtmlButton_Click(object sender, EventArgs e)
        {
            if (CsvDT2 != null && CsvDT2.Rows.Count != 0)
            {
                viewHtml2();
            }
            else
            {
                Session["ClientID"] = "1";
                if (Request.QueryString["id"] != null)
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?id=" + Request.QueryString["id"].ToString());
                }
                else
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx");
                }
            }

        }

        protected void AttributeFamiliesGridView_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView rw = e.Item.DataItem as DataRowView;
            if (e.Item.ItemIndex == 2 && (rw.DataView.ToTable().Rows.Count - 1) > 2)
            {


                HtmlTableRow trSpace1 = (HtmlTableRow)e.Item.FindControl("trSpace1");
                HtmlTableRow trSpace2 = (HtmlTableRow)e.Item.FindControl("trSpace2");
                trSpace1.Visible = true;
                trSpace2.Visible = true;
            }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (Request.QueryString["id"] == null || Request.QueryString["id"] == "" || Request.QueryString["id"] != ConfigurationManager.AppSettings["AdminID"].ToString())
                {
                    HtmlTableCell AttributeCount = (HtmlTableCell)e.Item.FindControl("AttributeCount");
                    HtmlTableCell AttributePercentage = (HtmlTableCell)e.Item.FindControl("AttributePercentage");
                    if (AttributeCount != null)
                    {
                        AttributeCount.Style.Add("display", "none");
                    }
                    if (AttributePercentage != null)
                    {
                        AttributePercentage.Style.Add("display", "none");
                    }

                }

            }
            if (e.Item.ItemType == ListItemType.Header)
            {


                if (Request.QueryString["id"] == null || Request.QueryString["id"] == "" || Request.QueryString["id"] != ConfigurationManager.AppSettings["AdminID"].ToString())
                {
                    HtmlTableCell AttributeCountHeader = (HtmlTableCell)e.Item.FindControl("AttributeCountHeader");
                    HtmlTableCell AttributePercentageHeader = (HtmlTableCell)e.Item.FindControl("AttributePercentageHeader");
                    if (AttributeCountHeader != null)
                    {
                        AttributeCountHeader.Style.Add("display", "none");
                    }
                    if (AttributePercentageHeader != null)
                    {
                        AttributePercentageHeader.Style.Add("display", "none");
                    }

                }
            }
        }

        class WantedAttributeFamily
        {
            private string _attributeFamily;

            public string AttributeFamily
            {
                get { return _attributeFamily; }
                set { _attributeFamily = value; }
            }
            private int _appearanceValue;

            public int AppearanceValue
            {
                get { return _appearanceValue; }
                set { _appearanceValue = value; }
            }

        }

        #region FileUpload2

        public void SetColorTab2(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            colordt.Columns.Add("Percentage");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage.ToString();
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Percentage", typeof(decimal));
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Percentage"] = GetPercentageofColor(color, colordt);
            }
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                if (color == "Transparent/White")
                {
                    row["Percentage"] = GetNeutralizedPercentageofColor(color, tempdt);
                    break;
                }
            }
            // Bind ColorGridView Of this Table
            tempdt.DefaultView.Sort = "Color";
            ColorDT2 = tempdt;


        }

        public void SetSubColorTab2(DataTable csvdatatable)
        {
            // This is Create SubColor Table 
            DataTable subcolordatatable = new DataTable();
            subcolordatatable.Columns.Add("Sub-Color");
            subcolordatatable.Columns.Add("Percentage");
            subcolordatatable.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {
                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Sub Color Name from database
                string SubColor = GetSubcolorName(RCode, GCode, BCode);
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);

                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = subcolordatatable.NewRow();
                r["Sub-Color"] = SubColor;
                r["Percentage"] = totalPixcelPercentage.ToString();
                r["Color"] = Color;
                subcolordatatable.Rows.Add(r);

            }
            DataTable tempdt = subcolordatatable.DefaultView.ToTable(true, "Sub-Color");
            tempdt.Columns.Add("Percentage");
            tempdt.Columns.Add("Color");
            // Calculated SubColor Percentage of Picture

            //  Calculated SubColor Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string subcolor = row["Sub-Color"].ToString();
                row["Percentage"] = GetPercentageofSubColor(subcolor, subcolordatatable);
                row["Color"] = GetMainColorSubColor(subcolor, subcolordatatable);
            }
            // Bind ColorGridView Of this Table
            SubColorDetailsDT2 = tempdt;
            SubColorDeatilsGridView2.DataSource = tempdt;
            SubColorDeatilsGridView2.DataBind();


        }

        public void SetColorBrightNess2(DataTable csvdatatable)
        {
            // This is Create SubColor Table 
            DataTable colorbrightnessdatatable = new DataTable();
            colorbrightnessdatatable.Columns.Add("Color");
            colorbrightnessdatatable.Columns.Add("Percentage");
            colorbrightnessdatatable.Columns.Add("Brightness");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                decimal brightness = Convert.ToDecimal(row["Column 11"].ToString());
                DataRow r = colorbrightnessdatatable.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage;
                r["Brightness"] = brightness;
                colorbrightnessdatatable.Rows.Add(r);

            }


            DataTable tempdt = colorbrightnessdatatable.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Brightness");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Brightness"] = GetBrightNesseofColor(color, colorbrightnessdatatable);
            }

            ColorBrightNessDT2 = tempdt;
            // Bind ColorGridView Of this Table
            ColorBrightNessGridView2.DataSource = tempdt;
            ColorBrightNessGridView2.DataBind();

        }

        public void SetColorAttributeTab2(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");

            DataTable attributedt = new DataTable();
            attributedt.Columns.Add("Attribute");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string ColorName = row["Color"].ToString();
                List<string> listofattribute = GetColorAttributesByColorName(ColorName);
                foreach (string attribute in listofattribute)
                {
                    DataRow attributerow = attributedt.NewRow();
                    attributerow["Attribute"] = attribute;
                    attributedt.Rows.Add(attributerow);

                }
            }

            DataTable tempattributedt = attributedt.DefaultView.ToTable(true, "Attribute");
            tempattributedt.Columns.Add("Count", typeof(int));
            tempattributedt.Columns.Add("Color Area Percentage", typeof(double));
            tempattributedt.Columns.Add("Total OffSet Percentage", typeof(double));
            tempattributedt.Columns.Add("Calculated Weight After Offset", typeof(double));

            //iteration to fill color area percentage
            foreach (DataRow row in tempattributedt.Rows)
            {

                string attributename = row["Attribute"].ToString();
                row["Count"] = GetAttributeCount(attributename, attributedt);
                //Jayant Pawar
                int direction = GetAttributeDirection(attributename);
                DataTable brightnessLevel = ColorAreaPercentageDT2 as DataTable;
                double areaPercentage = 0;
                foreach (DataRow rw in brightnessLevel.Rows)
                {
                    if (rw["Attribute"].ToString().Equals(attributename))
                    {
                        //if (direction == 1)//1 is id of Good 
                        //{
                        areaPercentage += Convert.ToDouble(rw["Color Area Percentage"]);
                        //}
                        //else if (direction == 2)//2 is id of Bad
                        //{
                        //    areaPercentage -= Convert.ToDouble(rw["Color Area Percentage"]);
                        //}
                    }
                }
                row["Color Area Percentage"] = areaPercentage;
            }

            foreach (DataRow row in tempattributedt.Rows)
            {
                string attributename = row["Attribute"].ToString();
                DataTable Offset = GetOffsetAttributes(attributename);
                double areaPercentage = (double)row["Color Area Percentage"];
                double totalOffPercentage = 0;
                bool isOffsetActivate = false;
                if (Offset != null)
                {
                    isOffsetActivate = GetUseOffset();
                    if (isOffsetActivate)
                    {
                        foreach (DataRow dr in Offset.Rows)
                        {
                            string Attribute1 = dr["Attribute1"].ToString();
                            string Attribute2 = dr["Attribute2"].ToString();
                            string offAttribute = null;
                            if (Attribute1 != attributename)
                            {
                                offAttribute = Attribute1;
                            }
                            if (Attribute2 != attributename)
                            {
                                offAttribute = Attribute2;
                            }
                            DataRow[] drs = tempattributedt.Select("Attribute='" + offAttribute + "'");
                            if (drs.Length > 0)
                            {
                                totalOffPercentage += (double)drs[0]["Color Area Percentage"];
                            }
                        }
                    }
                }
                row["Total OffSet Percentage"] = totalOffPercentage;
                row["Calculated Weight After Offset"] = areaPercentage - totalOffPercentage;
            }
            // Bind ColorAttributeGridView Of this Table
            tempattributedt.DefaultView.Sort = "Count DESC";
            ColorAttributeDT2 = tempattributedt;
            ColorAttributeGridView2.DataSource = tempattributedt;
            ColorAttributeGridView2.DataBind();
        }

        public void SetAttributeFamiliesTab2(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");

            DataTable attributedt = new DataTable();
            attributedt.Columns.Add("Attribute");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string ColorName = row["Color"].ToString();
                List<string> listofattribute = GetColorAttributesByColorName(ColorName);
                foreach (string attribute in listofattribute)
                {
                    DataRow attributerow = attributedt.NewRow();
                    attributerow["Attribute"] = attribute;
                    attributedt.Rows.Add(attributerow);

                }
            }

            DataTable attributefamiliesdt = attributedt.DefaultView.ToTable(true, "Attribute");
            DataTable attributeXAttributefamiliesdt = new DataTable();
            attributeXAttributefamiliesdt.Columns.Add("Attribute");
            attributeXAttributefamiliesdt.Columns.Add("Attribute Families");

            foreach (DataRow row in attributefamiliesdt.Rows)
            {
                string AttributeName = row["Attribute"].ToString();
                DataTable AttributesFamiliesdt = GetAttributesFamiliesByAttributeName(AttributeName);
                if (AttributesFamiliesdt != null)
                {
                    foreach (DataRow familiesrow in AttributesFamiliesdt.Rows)
                    {
                        DataRow attributeXAttributefamiliesrow = attributeXAttributefamiliesdt.NewRow();
                        attributeXAttributefamiliesrow["Attribute"] = familiesrow["Attribute"];
                        attributeXAttributefamiliesrow["Attribute Families"] = familiesrow["Attribute Families"];
                        attributeXAttributefamiliesdt.Rows.Add(attributeXAttributefamiliesrow);
                    }

                }

            }

            DataTable attributeXFamailiesTempdt = attributeXAttributefamiliesdt.DefaultView.ToTable(true, "Attribute Families");

            attributeXFamailiesTempdt.Columns.Add("Attribute");
            attributeXFamailiesTempdt.Columns.Add("Count", Type.GetType("System.Int32"));
            attributeXFamailiesTempdt.Columns.Add("Percentage", Type.GetType("System.Double"));
            attributeXFamailiesTempdt.Columns.Add("WeightedPercentage", Type.GetType("System.Double"));
            List<WantedAttributeFamily> wantedFamilyList = new List<WantedAttributeFamily>();
            decimal wantedFamilyMark = 0;
            if (Session["wantedFamilyList"] == null)
            {
                foreach (GridViewRow row in grdVwAttribute.Rows)
                {
                    CheckBox chk = row.FindControl("chk") as CheckBox;
                    if (chk.Checked)
                    {
                        DropDownList ddlAppearance = row.FindControl("ddlAppearance") as DropDownList;
                        Label lblAttributeFamily = row.FindControl("lblAttributeFamily") as Label;
                        WantedAttributeFamily wantedFamily = new WantedAttributeFamily();
                        wantedFamily.AttributeFamily = lblAttributeFamily.Text;
                        wantedFamily.AppearanceValue = Convert.ToInt32(ddlAppearance.SelectedValue);
                        wantedFamilyList.Add(wantedFamily);
                    }
                }
                Session["wantedFamilyList"] = wantedFamilyList;
            }
            else
            {
                wantedFamilyList = Session["wantedFamilyList"] as List<WantedAttributeFamily>;

            }
            foreach (DataRow row in attributeXFamailiesTempdt.Rows)
            {
                string AttributeFamilies = row["Attribute Families"].ToString();
                DataTable AttributeList = GetAttribute(attributeXAttributefamiliesdt, AttributeFamilies);
                string attributestr = string.Empty;
                int AttributeCount = 0;
                double percentage = 0;
                DataTable ColorAttributedatatable = ColorAttributeDT2 as DataTable;
                foreach (DataRow dr in AttributeList.Rows)
                {
                    string atrbte = dr["Attribute"].ToString();
                    double totalofPercentage = GetColorTotalFamilyPercentage(ColorAttributedatatable, AttributeList);
                    double colorPercentage = GetColorPercentageofAttribute(ColorAttributedatatable, atrbte);
                    double attributePercentage = 0;
                    if (totalofPercentage > 0)
                    {
                        attributePercentage = (colorPercentage / totalofPercentage) * 100;
                    }
                    dr["Percentage"] = attributePercentage;
                }
                AttributeList.DefaultView.Sort = "Percentage DESC";
                AttributeList = AttributeList.DefaultView.ToTable();

                foreach (DataRow dr in AttributeList.Rows)
                {
                    if (Math.Round(Convert.ToDouble(dr["Percentage"])) > 0)
                    {
                        AttributeCount++;
                        attributestr = attributestr + dr["Attribute"] + " " + String.Format("{0:00.00}", Math.Round(Convert.ToDouble(dr["Percentage"]), 2)) + "% </br>";
                    }

                    foreach (DataRow rw in ColorAttributedatatable.Rows)
                    {
                        if (rw["Attribute"].ToString().Equals(dr["Attribute"]))
                        {

                            percentage += Convert.ToDouble(rw["Color Area Percentage"]);
                        }
                    }

                }

                row["Attribute Families"] = row["Attribute Families"];
                row["Attribute"] = attributestr;
                row["Count"] = AttributeCount;
                row["Percentage"] = percentage;

            }

            attributeXFamailiesTempdt.DefaultView.Sort = "Percentage DESC";
            int? maxAttributeFamilies = GetMaxAttributeFamilies();
            if (maxAttributeFamilies != null)
                attributeXFamailiesTempdt = GetTopRecords(attributeXFamailiesTempdt, Convert.ToInt32(maxAttributeFamilies));

            //Calculate weighted percentage
            attributeXFamailiesTempdt = CalculatedWeightedAttributeFamily(attributeXFamailiesTempdt);

            //querystring value to be sent to pie chart api
            string attributeNamesForPieChart = string.Empty;
            string attributePercentagesForPieChart = "t:";

            /***************Chamge by Hanumant **************************/
            decimal total = 0;

            foreach (DataRow row in attributeXFamailiesTempdt.Rows)
            {
                string AttributeFamilies = row["Attribute Families"].ToString();
                if (wantedFamilyList.Count > 0)
                {
                    foreach (WantedAttributeFamily wantedFamily in wantedFamilyList)
                    {
                        if (AttributeFamilies == wantedFamily.AttributeFamily)
                        {
                            /*******Add by hanumant  for DBNUll Exception ****************/
                            if (row["WeightedPercentage"] != DBNull.Value)
                            {
                                wantedFamilyMark = wantedFamilyMark + Convert.ToDecimal((Convert.ToDouble(row["WeightedPercentage"])) * wantedFamily.AppearanceValue);
                            }
                            /*******Add by hanumant  for DBNUll Exception ****************/
                        }
                    }
                    wantedFamilyMark = Math.Round(wantedFamilyMark, 2);
                    WantedFamilyMark2 = wantedFamilyMark;
                }
                else
                {
                    if (Session["WantedFamilyMark2"] != null)
                        wantedFamilyMark = (decimal)WantedFamilyMark2;
                }
                if (row["WeightedPercentage"] != DBNull.Value)
                {
                    total += Convert.ToDecimal(row["WeightedPercentage"].ToString());
                    attributeNamesForPieChart += AttributeFamilies + " " + row["WeightedPercentage"].ToString() + "%|";
                    attributePercentagesForPieChart += row["WeightedPercentage"].ToString() + ",";
                }


            }

            decimal other = 100 - total;
            if (other > 0)
            {
                attributeNamesForPieChart += "Others" + " " + other.ToString() + "%|";
                attributePercentagesForPieChart += other.ToString() + ",";
            }

            if (Session["wantedFamilyList"] != null)
                lblWantedFamilyMark2.Text = "Marks of wanted families in the picture: " + wantedFamilyMark.ToString();

            //assigning piechart url to image
            string url = string.Empty;
            if (ImgFileName != null)
            {
                if (!string.IsNullOrEmpty(attributePercentagesForPieChart) && attributePercentagesForPieChart.Length > 2)
                    url = "https://chart.googleapis.com/chart?chs=400x100&chd=" + attributePercentagesForPieChart.Substring(0, attributePercentagesForPieChart.Length - 1)
                                     + "&cht=p3&chl=" + attributeNamesForPieChart.Substring(0, attributeNamesForPieChart.Length - 1) + "&chco=9568a3";
                pnlPieImg2.Style[HtmlTextWriterStyle.Display] = "block";
                pnlPieImg2.Attributes["style"] += "float: left; width: 50%;";
            }
            else
            {
                if (!string.IsNullOrEmpty(attributePercentagesForPieChart) && attributePercentagesForPieChart.Length > 2)
                    url = "https://chart.googleapis.com/chart?chs=650x200&chd=" + attributePercentagesForPieChart.Substring(0, attributePercentagesForPieChart.Length - 1)
                                   + "&cht=p3&chl=" + attributeNamesForPieChart.Substring(0, attributeNamesForPieChart.Length - 1) + "&chco=9568a3";
                pnlPieImg2.Style[HtmlTextWriterStyle.Display] = "block";
            }

            PieFileName2 = ImgFileName2.Substring(0, ImgFileName2.IndexOf(".") + 1) + "pieChart2.png";

            if (!string.IsNullOrEmpty(url))
            {
                SaveImageFromUrl("~/UpldImage/" + PieFileName2, url);
                imgPieChart2.ImageUrl = "~/UpldImage/" + PieFileName2 + "?uid=" + rndQuery.Next(0, 9999).ToString();
            }

            AttributeFamiliesDT2 = attributeXFamailiesTempdt;
            AttributeFamiliesGridView2.DataSource = attributeXFamailiesTempdt.DefaultView;
            AttributeFamiliesGridView2.DataBind();
        }

        //Jayant Pawar
        private void SetWhiteColorNeutralisetab2(DataTable csvdatatable)
        {

            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            colordt.Columns.Add("Percentage");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colordt.NewRow();
                if (Color == "Transparent/White")
                {
                    r["Color"] = Color;
                    r["Percentage"] = totalPixcelPercentage.ToString();

                    colordt.Rows.Add(r);
                }

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");
            tempdt.Columns.Add("Real Percentage");
            tempdt.Columns.Add("Neutralized Percentage");

            lblWhiteNeuMessage2.Visible = true;
            if (tempdt.Rows.Count < 1)
                lblWhiteNeuMessage2.Text = "White color neutralization is not activated.";

            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string color = row["Color"].ToString();
                row["Real Percentage"] = GetPercentageofColor(color, colordt);
                row["Neutralized Percentage"] = GetNeutralizedPercentageofColor(color, colordt);

                if (Convert.ToDouble(row["Real Percentage"]) > Convert.ToDouble(row["Neutralized Percentage"]))
                    lblWhiteNeuMessage2.Text = "White color neutralization (" + row["Neutralized Percentage"].ToString() + ") is activated.";
                else
                    lblWhiteNeuMessage2.Text = "White color neutralization is not activated.";

            }
            // Bind ColorGridView Of this Table

            WhiteColorNeutralization2 = tempdt;
            WhiteColorNeutralizationGridView2.DataSource = tempdt;
            WhiteColorNeutralizationGridView2.DataBind();

        }
        //Jayant Pawar
        private void SetColorAreaPercentagetab2(DataTable csvdatatable)
        {
            DataTable colorbrightnessdatatable = new DataTable();
            colorbrightnessdatatable.Columns.Add("Color");
            colorbrightnessdatatable.Columns.Add("Percentage");
            colorbrightnessdatatable.Columns.Add("Brightness");

            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                decimal totalPixcelPercentage = Convert.ToDecimal(row["Pixels pecentage"].ToString());

                DataRow r = colorbrightnessdatatable.NewRow();
                r["Color"] = Color;
                r["Percentage"] = totalPixcelPercentage;
                r["Brightness"] = Convert.ToDecimal(row["Column 11"].ToString());
                colorbrightnessdatatable.Rows.Add(r);

            }


            DataTable brightnessTable = colorbrightnessdatatable.DefaultView.ToTable(true, "Color");

            DataTable resultDT = new DataTable();
            resultDT.Columns.Add("Color");
            resultDT.Columns.Add("Attribute");
            resultDT.Columns.Add("Brightness");
            resultDT.Columns.Add("Calculated Brightness Level");
            resultDT.Columns.Add("Color Area Percentage");

            // Calculated Color Brightness of Picture
            foreach (DataRow row in brightnessTable.Rows)
            {
                string color = row["Color"].ToString();
                double colorPercentage = 0;

                //find color percentage from  ColorDT
                DataTable table = (DataTable)ColorDT2;
                DataRow colorRow = table.Select("Color='" + color + "'")[0];
                colorPercentage = double.Parse(colorRow["Percentage"].ToString());

                double brightness = Convert.ToDouble(GetBrightNesseofColor(color, colorbrightnessdatatable));
                DataTable colorAttribute = GetColorAttributes(color);

                if (colorAttribute != null)
                {
                    foreach (DataRow rw in colorAttribute.Rows)
                    {
                        DataRow dr = resultDT.NewRow();
                        double actualColorPercentage = colorPercentage;

                        double fromValue, toValue, maxValue, dominantValue = 1, ColorAreaPercentage = 0, brightnessLevel = 0; ;
                        fromValue = Convert.ToDouble(rw["BrightnessLevelFrom"]);
                        toValue = Convert.ToDouble(rw["BrightnessLevelTo"]);
                        maxValue = Convert.ToDouble(rw["BrightnessMaxValue"]);
                        if (fromValue.Equals(0) && toValue.Equals(0) && maxValue.Equals(0))
                        {
                            toValue = 1;
                            maxValue = 0.5;
                        }
                        dr["Color"] = color;



                        dr["Attribute"] = rw["Attribute"];
                        dr["Brightness"] = brightness;
                        if (brightness >= fromValue && brightness <= toValue)
                        {
                            if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(1)
                                || fromValue.Equals(0) && toValue.Equals(0.5) && maxValue.Equals(0.5)
                                  || fromValue.Equals(0.5) && toValue.Equals(1) && maxValue.Equals(1))
                            {
                                brightnessLevel = (brightness - fromValue) / (toValue - fromValue);
                            }
                            else if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(0)
                                    || fromValue.Equals(0) && toValue.Equals(0.5) && maxValue.Equals(0)
                                      || fromValue.Equals(0.5) && toValue.Equals(1) && maxValue.Equals(0.5))
                            {
                                brightnessLevel = (toValue - brightness) / (toValue - fromValue);
                            }
                            else if (fromValue.Equals(0) && toValue.Equals(1) && maxValue.Equals(0.5))
                            {

                                brightnessLevel = (0.5 - Math.Abs(0.5 - brightness)) / 0.5;
                            }

                            if (Convert.ToBoolean(rw["IsDominant"]))
                            {
                                dominantValue = getDominantValue();

                                //increase color percentage for dominant
                                actualColorPercentage = colorPercentage * dominantValue;
                            }

                            if (brightnessLevel < 0)
                                brightnessLevel = 0;

                            //changing as per latese discussion with client -- paresh
                            //ColorAreaPercentage = dominantValue * (1 + brightnessLevel);
                            ColorAreaPercentage = actualColorPercentage * (1 + brightnessLevel);
                        }


                        dr["Calculated Brightness Level"] = brightnessLevel;
                        dr["Color Area Percentage"] = ColorAreaPercentage;
                        resultDT.Rows.Add(dr);
                    }
                }
            }

            ColorAreaPercentageDT2 = resultDT;
            BrightnesLevelGridView2.DataSource = resultDT;
            BrightnesLevelGridView2.DataBind();
        }
        //Jayant Pawar
        private void SetContributedColorTab2(DataTable csvdatatable)
        {
            DataTable ColorAttributedatatable = ColorAttributeDT2 as DataTable;
            ColorAttributedatatable.DefaultView.Sort = "Color Area Percentage Desc";
            ColorAttributedatatable = ColorAttributedatatable.DefaultView.ToTable();
            DataTable Colordatatable = ColorDT2 as DataTable;
            int AttributeId = GetAttributeId(ColorAttributedatatable.Rows[0]["Attribute"].ToString());
            DataTable ColorsInAttribute = GetColorsByAttributes(AttributeId);
            DataTable result = new DataTable();
            result.Columns.Add("Color");
            result.Columns.Add("Percentage");
            string star = "<font style=\"color: red; font-weight: bold;\">*</font>";
            foreach (DataRow dr in ColorsInAttribute.Rows)
            {
                foreach (DataRow colordr in Colordatatable.Rows)
                {
                    if (dr["Color"].ToString() == colordr["Color"].ToString().Replace(star, string.Empty))
                    {
                        DataRow resultRow = result.NewRow();
                        resultRow["Color"] = colordr["Color"];
                        resultRow["Percentage"] = colordr["Percentage"];
                        result.Rows.Add(resultRow);
                    }
                }
            }
            result.DefaultView.Sort = "Percentage DESC";
            result = result.DefaultView.ToTable();
            //Old Coding to add * to color
            //foreach (DataRow colordr in Colordatatable.Rows)
            //{
            //    if (colordr["Color"].ToString().Replace(star, string.Empty) == result.Rows[0]["Color"].ToString())
            //    {
            //        colordr["Color"] = colordr["Color"].ToString() + star;
            //    }
            //    else
            //    {
            //        colordr["Color"] = colordr["Color"].ToString().Replace(star, string.Empty);
            //    }
            //}
            lblContributeColor2.Text = string.Format(lblContributeColor2.Text, result.Rows[0]["Color"].ToString());
            ColorDT2 = Colordatatable;
            ColorGridView2.DataSource = Colordatatable;
            ColorGridView2.DataBind();
        }

        protected void ExcelConnection2(string filename, string SheetName)
        {
            //// This Functon is read csv file and Data set  to Grid View

            DataTable datatable = new DataTable();

            // declare csv parser passing in path to file
            using (CsvReader csvData = new CsvReader(Server.MapPath("~/CApplication/" + filename)))
            {
                // set GridView to use DataTable returned from parser as the source
                // for it's data. True is passed in to signify that file contains a
                // header row which will name returned DataColumn's based on values
                // read in from header row.
                datatable = csvData.ReadIntoDataTable();
                SetCSV2(datatable);

            } // dispose of parser




        }
        public void SetCSV2(DataTable csvdatatable)
        {
            CsvDT2 = csvdatatable;
            ShowFileGridView2.DataSource = csvdatatable;
            ShowFileGridView2.DataBind();

        }

        public void DeleteCsvFile2()
        {

            if (FileName2 != null)
            {
                if (FileName2.ToString() != string.Empty)
                {
                    string filename = FileName2.ToString();

                    if (File.Exists(Server.MapPath("~/CApplication/") + filename))
                    {
                        FileName2 = null;
                        //Delete file 
                        File.Delete(Server.MapPath("~/CApplication/") + filename);
                    }
                }

            }

        }

        protected void DownloadButton2_Click(object sender, EventArgs e)
        {
            try
            {
                modalPage.Style[HtmlTextWriterStyle.Visibility] = "hidden";
                //if (FileName != null && Session["Filedata"] != null)
                if (FileName2 != null)
                {
                    if (FileName2.ToString() != string.Empty)
                    {
                        string filename = FileName2.ToString().Replace(".csv", ".xls");
                        // byte[] Filedata = (byte[])Session["Filedata"];
                        //// Download .csv file
                        //DownLoadCSV(filename, Filedata);// Old Method to download CSV file
                        DownloadXLS2(filename);
                    }
                    else
                    {

                        ErrorLabel2.Text = "Please upload Image File";
                    }
                }
                else
                {

                    ErrorLabel2.Text = "Please upload Image File";

                }
            }
            catch (Exception err)
            {

                ErrorLabel2.Text = err.Message.ToString();
            }
        }

        private void DownloadXLS2(string filename)
        {
            const string m_Http_Attachment = "attachment;filename=";
            const string m_Http_Content = "content-disposition";

            HttpResponse m_Response = HttpContext.Current.Response;

            m_Response.Clear();
            m_Response.ClearContent();
            m_Response.ClearHeaders();
            m_Response.Buffer = true;

            m_Response.AddHeader(m_Http_Content, m_Http_Attachment + filename);
            m_Response.ContentEncoding = Encoding.UTF8;
            m_Response.Cache.SetCacheability(HttpCacheability.NoCache);

            StringWriter m_StringWriter = new StringWriter();
            HtmlTextWriter m_HtmlWriter = new HtmlTextWriter(m_StringWriter);

            ShowFileGridView2.AllowPaging = false;
            ShowFileGridView2.HeaderStyle.Font.Bold = true;

            DataTable csvdatatable = CsvDT2 as DataTable;
            ShowFileGridView2.DataSource = csvdatatable;
            ShowFileGridView2.DataBind();
            ClearControls(ShowFileGridView2);
            ShowFileGridView2.RenderControl(m_HtmlWriter);

            string m_gridViewText = m_StringWriter.ToString();

            m_Response.ContentType = "application/vnd.ms-excel";
            m_Response.Write(m_gridViewText);
            m_Response.End();
        }

        protected void ShowFileGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = CsvDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["CSVLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["CSVLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["CSVLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["CSVLastSortExpression"] = e.SortExpression;
                    ViewState["CSVLastSortDirection"] = sSortDirection;

                    CsvDT2 = dataView.Table;


                    ShowFileGridView2.DataSource = dataView;
                    ShowFileGridView2.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message.ToString();
            }
        }

        protected void ColorGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["ColorLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["ColorLastSortExpression"] = e.SortExpression;
                    ViewState["ColorLastSortDirection"] = sSortDirection;

                    ColorDT2 = dataView.Table;


                    ColorGridView2.DataSource = dataView;
                    ColorGridView2.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message.ToString();

            }
        }

        protected void SubColorDeatilsGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = SubColorDetailsDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["SubColorDeatilsLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["SubColorDeatilsLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["SubColorDeatilsLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["SubColorDeatilsLastSortExpression"] = e.SortExpression;
                    ViewState["SubColorDeatilsLastSortDirection"] = sSortDirection;

                    SubColorDetailsDT2 = dataView.Table;

                    SubColorDeatilsGridView2.DataSource = dataView;
                    SubColorDeatilsGridView2.DataBind();
                }

            }
            catch (Exception err)
            {

                ErrorLabel2.Text = err.Message.ToString();

            }
        }

        protected void ColorBrightNessGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorBrightNessDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    string sSortDirection = string.Empty;

                    if (ViewState["ColorBrightNessLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorBrightNessLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorBrightNessLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;

                    ViewState["ColorBrightNessLastSortExpression"] = e.SortExpression;
                    ViewState["ColorBrightNessLastSortDirection"] = sSortDirection;

                    ColorBrightNessDT2 = dataView.Table;
                    ColorBrightNessGridView2.DataSource = dataView;
                    ColorBrightNessGridView2.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message.ToString();

            }
        }

        protected void ColorAttributeGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = ColorAttributeDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);

                    string sSortDirection = string.Empty;

                    if (ViewState["ColorAttributeLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["ColorAttributeLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["ColorAttributeLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;
                    ViewState["ColorAttributeLastSortExpression"] = e.SortExpression;
                    ViewState["ColorAttributeLastSortDirection"] = sSortDirection;

                    ColorAttributeDT2 = dataView.Table;
                    ColorAttributeGridView2.DataSource = dataView;
                    ColorAttributeGridView2.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message.ToString();

            }
        }

        protected void AttributeFamiliesGridView2_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dataTable = AttributeFamiliesDT2 as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);

                    string sSortDirection = string.Empty;

                    if (ViewState["AttributeFamiliesLastSortExpression"] == null)
                    {
                        sSortDirection = "ASC";
                    }
                    else
                    {

                        // not first sort operation requested for this report 
                        if (e.SortExpression == ViewState["AttributeFamiliesLastSortExpression"].ToString())
                        {
                            // not first click on this column so need to determine sort order requested 
                            if (ViewState["AttributeFamiliesLastSortDirection"].ToString() == "ASC")
                            {
                                sSortDirection = "DESC";
                            }
                            else
                            {
                                sSortDirection = "ASC";
                            }
                        }
                        else
                        {
                            // first click on new column 
                            sSortDirection = "ASC";
                        }

                    }
                    dataView.Sort = e.SortExpression + " " + sSortDirection;
                    ViewState["AttributeFamiliesLastSortExpression"] = e.SortExpression;
                    ViewState["AttributeFamiliesLastSortDirection"] = sSortDirection;

                    AttributeFamiliesDT2 = dataView.Table;
                    AttributeFamiliesGridView2.DataSource = dataView;
                    AttributeFamiliesGridView2.DataBind();
                }

            }
            catch (Exception err)
            {
                ErrorLabel2.Text = err.Message.ToString();

            }


        }

        protected void AttributeFamiliesGridView2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView rw = e.Item.DataItem as DataRowView;
            if (e.Item.ItemIndex == 2 && (rw.DataView.ToTable().Rows.Count - 1) > 2)
            {
                HtmlTableRow trSpace1 = (HtmlTableRow)e.Item.FindControl("trSpace1");
                HtmlTableRow trSpace2 = (HtmlTableRow)e.Item.FindControl("trSpace2");
                trSpace1.Visible = true;
                trSpace2.Visible = true;
            }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (Request.QueryString["id"] == null || Request.QueryString["id"] == "" || Request.QueryString["id"] != ConfigurationManager.AppSettings["AdminID"].ToString())
                {
                    HtmlTableCell AttributeCount = (HtmlTableCell)e.Item.FindControl("AttributeCount");
                    HtmlTableCell AttributePercentage = (HtmlTableCell)e.Item.FindControl("AttributePercentage");
                    if (AttributeCount != null)
                    {
                        AttributeCount.Style.Add("display", "none");
                    }
                    if (AttributePercentage != null)
                    {
                        AttributePercentage.Style.Add("display", "none");
                    }

                }

            }
            if (e.Item.ItemType == ListItemType.Header)
            {


                if (Request.QueryString["id"] == null || Request.QueryString["id"] == "" || Request.QueryString["id"] != ConfigurationManager.AppSettings["AdminID"].ToString())
                {
                    HtmlTableCell AttributeCountHeader = (HtmlTableCell)e.Item.FindControl("AttributeCountHeader");
                    HtmlTableCell AttributePercentageHeader = (HtmlTableCell)e.Item.FindControl("AttributePercentageHeader");
                    if (AttributeCountHeader != null)
                    {
                        AttributeCountHeader.Style.Add("display", "none");
                    }
                    if (AttributePercentageHeader != null)
                    {
                        AttributePercentageHeader.Style.Add("display", "none");
                    }

                }
            }
        }

        #endregion

        protected void WebFileButton2_Click(object sender, EventArgs e)
        {
            if (CsvDT != null && CsvDT.Rows.Count != 0)
            {
                downloadBoth();
            }
            else
            {
                Session["ClientID"] = "2";
                if (Request.QueryString["id"] != null)
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?download=true&id=" + Request.QueryString["id"].ToString());
                }
                else
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?download=true");
                }
            }

        }

        private void downloadBoth()
        {
            Session["ClientID"] = "3";
            if (Request.QueryString["id"] != null)
            {
                Response.Redirect("~/UpldImage/WebFile.aspx?download=true&id=" + Request.QueryString["id"].ToString());
            }
            else
            {
                Response.Redirect("~/UpldImage/WebFile.aspx?download=true");
            }
        }

        protected void ViewHtmlButton2_Click(object sender, EventArgs e)
        {
            if (CsvDT != null && CsvDT.Rows.Count != 0)
            {
                viewHtml2();
            }
            else
            {
                Session["ClientID"] = "2";
                if (Request.QueryString["id"] != null)
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx?id=" + Request.QueryString["id"].ToString());
                }
                else
                {
                    Response.Redirect("~/UpldImage/WebFile.aspx");
                }
            }
        }

        private void viewHtml2()
        {
            Session["ClientID"] = "3";
            if (Request.QueryString["id"] != null)
            {
                Response.Redirect("~/UpldImage/WebFile.aspx?id=" + Request.QueryString["id"].ToString());
            }
            else
            {
                Response.Redirect("~/UpldImage/WebFile.aspx");
            }
        }

        public void SaveImageFromUrl(string fileName, string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = null;
            try
            {
                response = request.GetResponse();

                byte[] content;

                Stream stream = response.GetResponseStream();

                using (BinaryReader br = new BinaryReader(stream))
                {
                    content = br.ReadBytes(500000);
                    br.Close();
                }
                response.Close();

                FileStream fs = new FileStream(Server.MapPath(fileName), FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                try
                {
                    bw.Write(content);
                }
                finally
                {
                    fs.Close();
                    bw.Close();
                }
            }
            catch
            {
            }
        }

        protected void btnViewDetail_Click(object sender, EventArgs e)
        {
            pnlPieImg1.Style[HtmlTextWriterStyle.Display] = "none";
            pnlPieImg2.Style[HtmlTextWriterStyle.Display] = "none";
            if (ImgFileName != null)
                Panel1.Style.Add("display", "block");
            if (ImgFileName2 != null)
                Panel2.Style.Add("display", "block");
            btnViewDetail.Visible = false;
        }

        protected void SaveButton1_Click(object sender, EventArgs e)
        {
            UrlAnalyseStep1();

            if (GetGoViaPayment())
                Response.Redirect("~/CreateTransaction.aspx");
            else
                Response.Redirect("~/" + Request.Url.PathAndQuery.Replace("&ref=new", "").Replace("ref=new&", "").Replace("?ref=new", "").Replace("ref=new", ""));
        }

        private void UrlAnalyseStep1()
        {
            string fileNamefromEXE = string.Empty;
            bool validUrl = false;
            string EnteredUrl = txtUrl.Text.ToLower();

            Uri url = null;
            try
            {
                try
                {
                    url = new Uri(txtUrl.Text);
                }
                catch
                {
                    EnteredUrl = "http://" + EnteredUrl;
                    url = new Uri(EnteredUrl);
                }
                /*********** Change made by Hanumant Add Uploaded Url to session variable **************/
                Session["Site_Url"] = txtUrl.Text;

                //Check whether given url is valid
                WebRequest request = WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                response.Close();
                validUrl = true;
            }
            catch
            {
                validUrl = false;
            }


            //if given url is valid
            if (validUrl)
            {
                //to get domain name
                // fileNamefromEXE = url.Authority + ".png";

                string[] splits = url.Host.Split('.');
                if (splits.Length > 2)
                    fileNamefromEXE = splits[1] + ".png";
                else
                    fileNamefromEXE = splits[0] + ".png";

                Process runMyapp = new Process();
                runMyapp.StartInfo.WorkingDirectory = Server.MapPath("~/CApplication/");
                runMyapp.StartInfo.FileName = Server.MapPath("~/CApplication/IECapt.exe");
                runMyapp.StartInfo.Arguments = " --url=" + EnteredUrl + " --out=" + fileNamefromEXE;
                //         runMyapp.StartInfo.Arguments = " --url=http://www.google.com/ --out=www.google.com.png";
                runMyapp.StartInfo.UseShellExecute = false;
                runMyapp.StartInfo.RedirectStandardOutput = true;
                runMyapp.Start();
                string output = runMyapp.StandardOutput.ReadToEnd();
                runMyapp.WaitForExit();
                runMyapp.Close();

                ImgFileName = fileNamefromEXE;
            }
        }

        public DataTable GetTopRecords(DataTable originalDT, int max)
        {
            DataTable cloneDataTable = originalDT.Clone();

            if (originalDT.Rows.Count > max)
            {
                for (int i = 0; i < max; i++)
                {
                    cloneDataTable.ImportRow(originalDT.Rows[i]);
                }

                return cloneDataTable;
            }
            return originalDT;
        }
    }
}

